Saved for later use = Declared function
A declared function is “saved for later use”, and will be executed later, when it is invoked (called).
What is a Function Expression?
A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:
var x = function (a, b) {return a * b};
After a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
Function Expression VS. Function Statement
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code.
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
Similar to the var statement, function declarations are hoisted to the top of other code.
Hoisting is a concept which enables us to extract values of variables and functions even before initialising/assigning value without getting error and this is happening due to the 1st phase (memory creation phase) of the Execution Context.
getName(); // Namaste JavaScript
console.log(x); // undefined
console.log(getName); // f getName(){ console.log("Namaste JavaScript); }
function getName(){
console.log("Namaste JavaScript");
}
Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.
getName(); // Uncaught TypeError: getName is not a function
console.log(getName);
var getName = function () {
console.log("Namaste JavaScript");
}
// The code won't execute as the first line itself throws an TypeError.
Benefits of Function Expressions
There are several different ways that function expressions become more useful than function declarations.
- As closures - Function bundled along with it's lexical scope is closure.
- As arguments to other functions
- As Immediately Invoked Function Expressions (IIFE)
Top comments (0)