I came across below code by following a tutorial.
const increment = (function(){
return function incrementbytwo (number){
return number+2;
}
})();
console.log(increment(1));
The above outputs 3.
My problems are
incrementbytwo
receive a parameter from outside since it's a Self-Executing Anonymous Functions
?1) The self executing IFFE results in the creating of a function statement being assigned to the increment
identifier. It is exactly the same as:
const increment = function incrementbytwo (number){
return number+2;
}
I should add, in case you don't know, that increment
is block scoped to the enclosing code block (const), while incrementbytwo
is function scoped to the function and is not accessible outside the function itself (due to the nature of the function expression).
2)
incrementbytwo(number)
that expects a number as a argumentincrement
(hence is a function expression. The function expression uses the same signature as the function statement - therefore takes a single argument that it passes into the function.3) There isn't one.
Here is my understanding of this:
I will start with #2 on your list, as it will make this easier. What you have, is a self-executing anonymous function that RETURNS a stored function.
increment
constant to the returned result of the anonymous function's execution.incrementbytwo
and THIS is assigned to your increment
constantincrement
constant, which is now incrementbytwo(number)Your code above is just a standard function declaration with extra steps at declaration.
const increment = function increment(number){
return number+2;
}
console.log(increment(1));
There is no production use for this exact code scenario as far as I know (Roast me in the comments if I am wrong)
©2020 All rights reserved.