Function Expression

A function expression is when a function is assigned to a variable.
This is very similar to a function declaration except the name can be omitted to create an anonymous function.
A function expression is run as soon as it is defined.
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));


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.
This is called a Function Literal

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


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];
}


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



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