Intro to JavaScript, CSS, jQuery ICS 215
Data Types • Number • String • Boolean • Object • Array • Function • Math • Date • RegExp • Null • Undefined • Error
Numbers • Numbers are in floating format • no integer type in JS • Note: 0.1 + 0.2 = 0.30000000000000004 • Math object provides mathematical operations • var value = Math.sin(3.5); • var area = Math.PI * r * r; • Constants • PI, E, SQRT2, SQRT1_2, LN2, LN10, LOG2E, LOG10E • Functions • sin, cos, tan, acos, asin, atan, atan2 • sqrt, exp, log, pow • random • max, min, round, ceil, floor, abs
Numbers • parseInt() converts a string to an integer • var i = parseInt(“123”, 10); // i = 123 • parseFloat()converts a string to a float • var x = parseFloat(“12.34”); // x = 12.34 • NaN (Not a Number) special value • var i = parseInt(“aloha”, 10); // i = NaN • isNaN(x) checks for NaN • Infinity special value • var x = 1/0; // x = Infinity
Strings • Sequence of Unicode characters • no character data type • delimited by "" or '' • use \' within '' and \" within "" • + operator concatenates • gotcha: an expression becomes a string, if just one portion is a string • var notANumber = 1 + "2"; // = "12" • Functions (there are more) • substr, substring, concat, replace, slice, split • toLowerCase, toUpperCase • charAt, indexOf, lastIndexOf • match, search
Boolean • trueand falsevalues • automatic conversion • false • false, 0, '', "", NaN, null, undefined • true • everything else • that's a gotcha! • Boolean() – use to convert programatically
Comments • inline comments • everything after // till the end of the line • var someCode; //comment from now on • block comments • everything after /* till */ • var someCode; /*comment*/ alert('code again'); • Document with code • use empty lines sparingly, comment! • document each function, each parameter
Operators • arithmetic • +, -, *, /, % • comparisons • ==, >, >=, <, <=, • ===, !== (is safer than == and != ) • boolean • !, &, | • &&, || (short-circuit) • ? : (ternary) • string • +
Assignment with Operators • increment • ++ • i++; is same as i = i + 1; • decrement • -- • i--; is same as i = i - 1; • other • +=, -=, *=, &=, &&= etc. • i *= someExpr; is same as i = i * someExpr;
Short-Circuit && and || • evaluates left-hand side first; right-hand side only if necessary • && • var b = b1 && b2; • same as • var b = b1;if (b1 === false) {} else {b = b2;} • or • var b = b1 === false ? b1 : b2; • || • var b = b1 || b2; • same as • var b = b1;if (b1 === true) {} else {b = b2;} • or • var b = b1 == true ? b1 : b2;
Comparisons Mess • Strange results: • null == null // true • undefined == undefined // true • NaN == NaN // false • null == undefined // true • new String("a") == "a" // true • new String("a") == new String("a") // false • useful: forced comparisons • String: • "" + a == "" + b • Number: • +a == +b • Boolean: • !a == !b
Variables • no type-checking • automatic conversion • var value = 'Aloha'; • value = 2013; // no error • declare variables with var • undeclared variables are in global scope (not good!) • a variable declared within a block is defined in surrounding function
Arrays • Arrays are special objects • var a = [“dog”,“cat”,“hen”]; • var a = new Array(); • var a = []; • array indices start at 0 • array size is dynamic • a.push("bird"); • array has length • console.log(a.length); // 3 • length = the highest index + 1 • usefull functions • push, pop • shift, unshift • reverse
Simple Objects • Objects are similar to hashesset of key:value pairs • var person = {}; • var person = new Object(); • person = {name: "Jan", single:false, "kids":2}; • keys can be strings (or simple names) • Direct access to fields • console.log(person.name); // Jan • person.kids += 2; // = 4 • person.last = "Stelovsky"; • a field can be added dynamically • Dynamic access to fields • Objects are special arrays, only with string indices • person["kids"] += 2; // = 6 • for (var key in person){ console.log(key + ':' + person[key]);}// name:Jan// single:false// kids:6// last:Stelovsky
Control Structures • loops • while • do-while • for • for (vari = 0; i< a.length; i++) { a[i] = 0;} • for (varkey in object) { object [key] = 0;} • branches • if-else • switch-case • can compare strings and use an expression in case
Functions • Similar to Java methods, Perl subs • block of code that can be called elsewhere • can have parameters • can return a value • can be nested • But is a "first class" object • can be assigned to a variable • can be passed as parameter to another function • can be returned from a function • meta-programming • array's element can be a function • object's field can be a function • as a variable, parameter, array element or object fieldcan be anonymous • without a name • Note: a function must be defined before it's called
Functions cont. • function sum(x,y){ return x + y;}sum(3,4); // 7 • not all parameters need to occur in a call • function sum(x,y){ return x + (y ? y : 0);}sum(4); // 4 • number of parameters can be arbitrary • function sum(){ var sum_ = 0; for (var i = 0; i < arguments.length; i++) { sum_ += arguments[i]; } return sum_;}sum(1, 2, 3, 4); // 10
Function Variables, Parameters • Functions can be assigned • var sum = function(x,y){return x + y;};sum(3,4) // 7 • Note: anonymous function • Functions can be passed as parameter • function plot(f){ for (var x = x1; x < x2; x++){ draw_point(x, f(x)); }}plot(Math.sin);plot(function(x){return x*x + 1/x;}); • Note: anonymous function
Functions in Arrays • Function can be used as array element • var polynomials = [ function(x){return 1;}, function(x){return x;}, function(x){return x*x;}, function(x){return x*x*x;} ];polynomials[4] = function(x){ return x*x*x*x; };polynomials[4](3); // 81
Function Returned • Example: sample polynomial • function polynomial(power) { return polynomials[power];}polynomial(4)(3); // 81for (var n = 0; n < polynomials.length; n++){ console.log(polynomial(n)(3));}// 1 3 9 27 81
Functions in Objects • Function can be used as object field / property • var arithm = { PI: 3.14, plus: function(x,y){return x + y;}, minus: function(x,y){return x - y;}, times: function(x,y){return x * y;}, divide:function(x,y){return x / y;}, modulo:function(x,y){return x % y;}};arithm.plus(arithm.times(2,3),arithm.PI);// (2*3)+3.14 = 9.14
Closures • An inner function has access to outer function's variables • Outer function's variables exist while inner function exists • function closure(){ var n = 0; function inner(){ n++; console.log(n); } for (var i = 0; i < 4; i++){ inner(); }}closure();// 1 2 3 4
Closures • Let's return the inner function: • function closure(){ var n = 0; return function(){ n++; console.log(n); }}var inner = closure(); • Outer function's ceased to execute • for (var i = 0; i < 4; i++){ inner();}// 1 2 3 4 • But it's variables are around because inner function needs them!