yaru
yaru

Reputation: 1320

Why inner functions are called before outer functions?

In the code example below the output will be 3 2 1. Why not 1 2 3? Doesn't an opening parentheses symbol ( in a1( call indicate that this function must be invoked first? And all stuff inside parentheses, i.e. a2(a3(50)) must go as a number parameter to function a1 ?

function a1(number) {
  console.log("1");
  return number;
}

function a2(number) {
  console.log("2");
  return number;
}

function a3(number) {
  console.log("3");
  return number;
}

a1(a2(a3(50)));

Upvotes: 0

Views: 261

Answers (3)

Brett East
Brett East

Reputation: 4322

Yes the ( in a1() means to call it. And the very first thing that it does is to evaluate the parameter that is passed in. In this case a function call is passed in, that is a function with its own set of ().

That means that a1 needs to wait for a2 to be evaluated so that it can pass in the returned value from calling a2 into a1 as a param. The same goes for a2 accepting a3 as a parameter.

In the following psuedo code you can see:

function a1(number) {
  return number;
}

If you call this as such:

a1(2+3) // you can't just run a1(2)

You have to evaluate 2+3 first, and to evaluate a function called with parenthesis, you have to run the entire function. In your case that function logs something to the console.

Edit: Adding this below because it was in the comments and it the answer that OP was looking for.

The first function call actually starts a new execution context and that function jumps to the top of the 'call stack', but the first thing that function does is evaluate the argument. If that argument is a function, then it kicks off its own execution context and it moves to the top of the 'call stack' and so on. And as stacks work on a 'last in, first out' basis, the most recent one has to be evaluated first.

Upvotes: 3

Shubham Gupta
Shubham Gupta

Reputation: 2646

So basically what you have done is you have passed the output of one function as an argument to another function.

In order to pass value returned by a3 it must be executed first. Hence you get 3 2 1 as output.

Upvotes: 0

Quentin
Quentin

Reputation: 944204

The JS engine has to run the function so it can get its return value so it can pass that to the next function.

Upvotes: 5

Related Questions