C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have nothing in common except their “parents”
Variables (or identifiers) Values stored in computer memory Value can vary over time Reserved Words and Keywords part of the JavaScript language-- Variable Example: employeeName
JavaScript Variables Two ways to create: Use var to declare the variable var employeeName; Use the assignment operator to assign the variable a value employeeName = “Ric”;
Variable name syntax rules (like C:Java,etc.) Cannot use reserved words & spaces Must begin with one of the following: Uppercase or lowercase ASCII letter Dollar sign ($) or underscore (_) Variables are case-sensitive Can use numbers, but not as first character
Variable Naming Conventions Use underscore or capitalization to separate words of an identifier employee_first_name employeeFirstName
legalIllegal my_variable $my_variable __my_variable my_variable2 myVariable $ my%_variable 2my_variable my_#variable ~my_variable my+variable
abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with
C++ / Java Comments DOCUMENT your code + use it for testing Line comments // ignore all text to the end of the line Block comments /* ignore all text between these symbols */
/* commented out code*/ code //line comment code //########## separator ########## /*____________________________________ __ Section comment ______________________________________ */
a clever trick: /* */ code // */ /* *x/ commented out code // */
C Statements; Statements are ALWAYS terminated with ; New lines mean nothing; are ignored. Extra ; are harmless but it is parsed javascript and downloaded… so it has a cost Browsers tolerate missing ; but don’t push your luck with bad habits!
Strings String Literals contained in quotes “ ” or single quotes ‘ ’ Strings can be: Used as “literal” values Assigned to a variable empty “”
Using HTML tags in strings Use HTML tags to format strings Tag must be contained inside string quotes var newString = ‘ ’; 2 kinds of quotes saves you from having to escape quotes \”
Escape Characters Escape Squence Character \\Backslash (\) \nNew Line (unix-use this one) \tTab \’ Single quotation mark / Apostrophe \”Double quotation mark There are others
Concatenating strings Concatenation operator: + var oneString = “one”; var anotherString = oneString + “, two, three, …”; Assignment operator: += var oneString = “one”; oneString += “, two, three, …”;
Numbers Number Literals just type a number Abstract - no int, float, or small size limits Math Object contains a function library from random to trig functions
Assignment Operators Syntax very similar to C/Java, but: var x = 'dog'; var y = 'dog'; x= 5; y= my_function();
OperatorDescription =Assigns value of right to left +=Adds right value to left -=Subtracts right value to left *=Multiplies right value to left /=Divides right value into left %= Divides right value into left returns remainder
var x = 4; var y = 5; x += y; // x becomes 9 var a = "Hello"; var b = " World!"; a += b; // a becomes "Hello World!"
! is it null, undefined, 0, false, “” ()? ( test )? if true this : if false this like if statement but compact, faster + - * / % && || same as java Other operators
Ternary conditional var x = ( true ) ? ‘hello world’ : 47 ; data types can be mixed Technically, it is just ? : but everybody uses the ()
Decision Making if ( condition statement ) { statement(s); if( condition statement ) { statement(s); } else {statement(s);} }
conditionals only want false DOES NOT RUN next code block: if( false ){} if( 0 ){} if( “” ){} if( null ){} var x; if( x ){}
Comparison Operators Used to compare two operands for equality and if one numeric value is greater than another Can mix types! Auto type conversion is possible. Compare that to Java!
OperatorDescription ==true if equal !=not equal >greater than <less than >=greater or equal to <=less or equal to
Common Typoo = is not == if( x = 5 ){} y= ( x = 5 ) true : false; valid code; but not expected result
Custom Functions Function is similar to Java method Individual statements grouped together to form a specific procedure Allows you to treat the group of statements as a single unit
Defining Functions 1. function + name (identifier) 2. Parameter list in parentheses () variables live within the function block Zero or more order matters 3. Code block defined by braces { }
function printC(company1, company2, company3) { document.writeln(company1); document.writeln(company2); document.writeln(company3); }
Calling Functions “function invocation” or “function call” f() f( parameter1, 2, 3, 4 ) Used in a statement ; denotes the end of a statement many javascript interpreters handle ; mistakes - it does not mean you’re correct
Returning a value A function could return nothing return; var returnValue = square(x); return x*x;
function square(x){ return x*x; } var result= square(4); alert(result); // displays 16 alert( square(4) ); //also displays 16
Loops quick review - C derived
for Like Java, C, C++, Objective-C, C#... for( initialize; test; last ) initialize is run first, only once test is evaluated EACH time Runs before the loop-- if false we stop last is run at the END of EACH loop
var i; for( i=0; i< 50; ++i) { document.writeln(”this is #” + i); }
while while( test ) loops until test is false as basic as it gets
var i = 0; while( i< 50) { document.writeln(”this is #” + i); ++i; }
do while do {code} while( test ) loops until test is false runs code at least 1 time created just to make life easier
var i = 0; do { document.writeln(”this is #” + i); ++i; }while( i< 50);
continue & break continue; Halts a looping statement and restarts the loop with the next iteration could be called “skip” or “blowrev” break; jumps out of loop or switch
Review Initialization statements setup loop Evaluate conditional statement: 0, false,””, null, undefined → stop inside loop: run statement(s) which impact conditional statement for( x=1; x; x+1) {alert(‘infinite loop’);}