JavaScript has two different ways of creating functions. Function declarations have been used for a long time, but function expressions have been gradually taking over.
function funcDeclaration() {
return ‘A function declaration’;
}
var funcExpression = function () {
return ‘A function expression’;
}
Similar to the var statement, function declarations are hoisted to the top of other code. Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.
Normally function declarations and function expressions can be used interchangeably, but there are times when function expressions result in easier to understand code without the need for a temporary function name.
Benefits of Function Expressions
There are several different ways that function expressions become more useful than function declarations.
· As Closures
· As arguments to other Functions
· As Immediately Invoked Function Expressions (IIFE)
IIFE’s are used to help prevent your functions and variables from affecting the global scope. All the properties within are scoped to the anonymous function. This is a common design basic interview questions for ui developer pattern that’s used to prevent your code from having unwanted or undesired side-effects elsewhere.