
There are two ways to declare functions in JavaScript: function expressions and function declarations. The first can be stored in a variable, the second can be reused anywhere in your code. You are probably used to seeing function declarations, they are what I knew best myself, but it is worth knowing that there is another way.
This article may be updated from time to time
Function declaration
Unlike a function expression, a function created with a function declaration can be called before it has even been declared, because the interpreter looks for variables and function declarations before working through the rest of your script. Once a function is declared, you can call it later in your code, but to be able to call it, you have to give it a name.
function addition(a, b) {
return a + b;
};
var calcul= addition(2, 5) ;Function expression
A function expression is a function that is created, stored and handled like a variable. Function expressions usually have no name, which is why they are called anonymous functions. The function is stored in a variable and can be called like any other function. Be aware, though, that the function is only processed when your browser interpreter reads the declaration. That means you cannot call the function before the interpreter has read it, and that any code appearing up to that point could change what happens inside it.
var addition = function(a, b) {
return a + b;
};
var calcul = addition(2, 5) ;Immediately-Invoked Function Expression
Commonly called an IIFE, every variable declared inside this anonymous function is isolated from the variables of other scripts that might share the same name. This comes down to variable scope. Here is an example of an IIFE.
var addition = (function(){
var a = 10;
var b = 20;
return a + b;
}());- The brackets around our function make sure it is treated as an expression.
- The two brackets at the end,
(), tell the interpreter to run our function immediately.
We mostly use it as soon as we start writing a new script, to keep all of our code isolated.
When should you use anonymous function expressions?
They are used for code that has to run only once, rather than being called again and again by other parts of the script. An anonymous function expression can be used:
- to avoid conflicts between two scripts that might use the same variable names as ours,
- as an argument when a function is called (to work out the value of that function);
- to run a task when an event occurs,
- to assign the value of a property to an object.
···


