Functions


Literal

var myVar = function () { 
   return arguments[0] + arguments[1];
}



Named

This function takes 2 parameters
This is useful for recursive functions to allow them to call themselves

function add(x, y) 
{
   var z = x + y;
   return z;
}

var sum = add(1,2)


Named with Return

This function takes 2 parameters

var add = function (x, y) 
{
   var z = x + y;
   return z;
}

var sum = add(1,2)


Anonymous without a Return

This function has no parameters
Functions do not need names and can be passed around anonymously
Anonymous functions are used heavily in jQuery

( function() { 
   //some code
} )


var myResult ( function() { 
   return arguments[0] + arguments[1];
} ) (1,2);
alert(myResult);


alert( ( function() { 
   return
} ) (1,2) ) ;



Anonymous Self Executing

This will run everytime the file loads, notice the extra parentheses at the end.

( function() { 
   //some code
} ) ();


Parameters

there is built-in "arguments" object
too many - ignored
too few - undefined



Closure

Its scope at the time of declaration
not at the time of calling ??



Hoisting

Functions can be declared any where in a file
Always put to the top of the file



© 2017 Better Solutions Limited. All Rights Reserved. © 2017 Better Solutions Limited

PrevNext