Function Expression

A function expression is when a function is assigned to a variable.
Also called a Function Literal
This is very similar to a function declaration except the function name has been omitted.
Function expressions are not hoisted.
You do have to include a semicolon at the end.

var IsEven = function (num) { 
   return num % 2 === 0;
};
console.log(IsEven(2));

Anonymous Function Expression

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 myVar = function() { 
   return arguments[0] + arguments[1];
}


Named Function Expression

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 name of the function only exists inside the function scope, it is not accessbile outside.


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);



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


This is a named function expression

var checkNum = { 
'isEven' : function IsEven(num) {
      console.log(num);
      return num % 2 === 0;
   }
};
console.log(checkNum.IsEven(2) ); // true

The variable the function expression is assigned to will have a 'name' property

var aa = function() {} 
console.log(aa.name); // aa

The name will not change if it is assigned to another variable

var bb = aa; 
console.log(bb.name); // aa

If the function name is present then the name will be the function name.
If the function name is anonmous the variable name will be used.

var cc = function dd() {}; 
console.log(cc.name); // dd


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