Closure Factory function

How Closures work when we return functions.

First, we push the global execution context onto the stack.

We start with the Creation Phase of global and place these things into memory:

– ‘this’ references the global object
– sets outer reference
– makeGreetings function definition
– var greetEn = undefined
– var greenSp = undefined

Then in the Execution Phase of Global, we go down line by line.

makeGreetings is a function definition which was already taken care of in the creation phase. greetSp is already in memory. Then we see code line //1 )

It’s an invocation. We push this execution onto the stack.


The invocation has parameter ‘language’ that references literal string ‘en’.

For Creation Phase of makeGreetings, we put variable ‘language’ in memory. We set the ‘this’ reference to the global object. Set the outer reference. Then we put the whole anonymous function in memory.

Now, we do the Execution Phase of makeGreetings. It doesn’t do anything and simply return the anonymous function that is in memory.

We finish processing makeGreetings(‘en’) and gets the returned anonymous function, we point our greetEn reference to it.

We then move on to code line // 2)

At this point, makeGreetings(‘en’) pops from the stack because it has finished execution.

Now we come to code line //3

It is an invocation of function greetEn(‘bob’) so we push it onto the execution stack.

For greetEn’s Creation Phase, we have a parameter so we put name = ‘bob’ in memory.
– The ‘this’ references the global object.
– We set the outer reference

In its greetEn’s Execution Phase, it will first look at variable language to see what it is. In memory, variable language is referencing a literal string ‘en’. It will then trigger the if statement and we execute the log statement.

We see that the log uses variable name. In memory, name is ‘bob’. Thus we log out:

‘Hello Bob my friend’.

After greetEn finishes, our execution moves on to the next line and greetEn is popped from the stack.

greetEn execution context is popped from the stack.
parameter ‘name’ is popped along with greetEn execution stack because no one else is referencing it.
var greetEn is still referencing the anonymous function in memory.
language is still there and set to ‘en’.
makeGreetings function definition is still in memory.