Checking if a Variable Exists
var result = ''; if (somevar){result = 'yes';}
A better way to check if a variable is defined is to use typeof.
if (typeof somevar !== "undefined"){result = 'yes';} result
Because somevar is undefined.
Agruments
var result = sum(1, 2); result;
JavaScript is not picky at all when it comes to parameters. If you pass more parameters than the function expects, the extra parameters will be silently ignored:
>>> sum(1, 2, 3, 4, 5)
3
>>> function args() { return arguments; }
>>>args();
[]
args(1,2,3,4,true,"ninja")
[1, 2, 3, 4, true, "ninja"]
By using the arguments array you can improve the sum() function to accept any number of parameters and add them all up.
function sumOnSteroids() { var i, res = 0; var number_of_params = arguments.length; for (i = 0; i < number_of_params; i++) {? res += arguments[i]; } return res; }
sumOnSteroids(1, 1, 1);=3
sumOnSteroids(1, 2, 3, 4);=10
var scope
var a = 123; function f() { ? alert(a); var a = 1; alert(a); } f();
You might expect that the first alert() will display 123 (the value of the global variable a)
the second will display 1 (the local a).
The first alert will show "undefined". This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.[color=red][/color]
CallBack Function
function invoke_and_add(a, b){ return a() + b(); } function one() { return 1; } function two() { return 2; } invoke_and_add(one, two);
When you pass a function A to another function B and B executes A, it's often said that A is a callback function. If A doesn't have a name, then you can say that it's an anonymous callback function.
function multiplyByTwo(a, b, c, callback) { var i, ar = []; for(i = 0; i < 3; i++) { ar[i] = callback(arguments[i] * 2); } return ar; } function addOne(a) { return a + 1; }
myarr = multiplyByTwo(1, 2, 3, addOne);
Self-invoking Functions
( function(name){ alert('Hello ' + name + '!'); } )('dude')
One good reason for using self-invoking anonymous functions is to have some
work done without creating global variables.
A drawback, of course, is that you cannot execute the same function twice