Self-Executing Anonymous Functions Parameter From Outside Scope

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

  1. How does the inner incrementbytwo receive a parameter from outside since it's a Self-Executing Anonymous Functions?
  2. Step by step explanation of how this is executed.
  3. What would be a real-world scenario to use a function like this?

Answers:

Answer

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)

  • 1) The right hand side is evaluated - and returns a function statement declaring incrementbytwo(number) that expects a number as a argument
  • 2) The assignment of that function statement is made to increment (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) Calling increment(1) makes the magic happen.

3) There isn't one.

Answer

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.

  1. You call to assign the increment constant to the returned result of the anonymous function's execution.
  2. When the Anon function gets executed it returns the function incrementbytwo and THIS is assigned to your increment constant
  3. You then call to execute the stored function within the increment 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)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.