// return a square of given chars function square(size, char) { var char = char || '*'; var s = ''; for(var i=0; i<size; i++) { for(var j=0; j<size; j++) { s += char; } s += '\n'; } return s; } console.log(square(10));
Function definiiton in javascript is not the same as in C.
function square(size, char) {...} // YES function square(var size, var char) {...} // NO
Use the special variable 'arguments' to take in variable number of function parameters
// dump everything passed into the function function dump() { return arguments; } console.log(dump(233, 'naive', true));
Output
D:\code\js>node square.js { '0': 233, '1': 'naive', '2': true }
Hoisting - variable delcarations are moved to the very beginning.
var a = 233; function f() { // actually there is a "var a;" and this is called hoisting alert(a); // undefined var a = 666; // * alert(a); // 666 } f();
!!! Variables declared without a "var" is considered global !!!
A function can even modify itself in javascript.
// a function that can modify itself function transform() { console.log("original function trnasform()"); transform = function () { console.log("mutated function tansform()"); } } transform(); transform();
Output
D:\code\js>node square.js original function trnasform() mutated function tansform()
Closure in javascript - first shot
var outer = 233; function foo() { var inner = 666; return outer; } console.log(foo()); outer = 555; console.log(foo()); // OUTPUT D:\code\js>node square.js 233 555
Another interesting example of closure
function foo(param) { var goo = function () { return param; } param++; return goo; } var g = foo(233); g(); // 234
Another "boring" example
function gpa_factory() { var current_gpa = 3.0; return function() { current_gpa += 0.1; console.log('Due to your hard work, your GPA now is ', current_gpa.toString().substr(0, 4)); }; } var study = gpa_factory(); for(var i=0; i<10; i++) { study(); }
An exercise from the book I am reading.
var a = 1; function f() { function n() { console.log(a); } n(); // undefined var a = 2; n(); // 2 } f();
ref: Object-Oriented Javascript 2nd Edition, Stoyan Stefanov.
Last word:
Javascript looks like a lot of fun!