Declaring



You can use the 'return' to exit the function immediately, any other lines of code will be ignored.
Function overloading is not allowed, the last function (from top to bottom is used)
There is parameter flexibility


Named without Arguments

function doSomething() { 
   alert('my message');
}

doSomething();


Named with Arguments

This function takes 2 parameters
Often called the standard function declaration

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

var sum = add(1,2)

Named without Return

A function that does not have a specific return will return undefined

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

Named and Assigned

This function cannot be invoked using its name. You must use the variable name.
If you have assigned it to a variable you cannot call the function name
The function name can be omitted but it is best practice to always include a name so it appears on the call stack when debugging.
This is called a Function Literal

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


Anonymous and Assigned

The function name can be omitted but it is best practice to always include a name so it appears on the call stack when debugging.

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

Anonymous without 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
} )


Anonymous with Return

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


Anonymous and Invoked Immediately

Invoked immediately is also known as self executing

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

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

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

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




© 2018 Better Solutions Limited. All Rights Reserved. © 2018 Better Solutions Limited TopPrevNext