How is this 15?

- 1 answer

Ad

how does this execute to 15??

What is the step by step process that the engine is running?

function doSomething(a) {
    function doSomethingElse(a) {
        return a - 1;
    }

    var b;

    b = a + doSomethingElse( a * 2 );

    console.log( (b * 3) );
}

doSomething( 2 ); // 15
Ad

Answer

Ad
  1. The call to doSomething() is made, with 2 as the parameter (bound to a in the function).
  2. The call to doSomethingElse() is made, with 4 (a * 2) as the parameter, bound to the symbol a in that inner function.
  3. The inner function returns 3 (a - 1).
  4. The doSomething() function then adds its a (still 2) to the result, giving 5, and assigns that to b.
  5. The console.log() call is made, with 15 as the argument (b * 3).
Ad
source: stackoverflow.com
Ad