DEV Community

kim-jos
kim-jos

Posted on • Updated on

How do Functions work in JS?

What happens when a function is invoked?

Let's start off with a simple problem. There are three variables named x in the following code. Which values do you think will be returned when the functions are invoked and the variable is printed in the console? The answer is provided below as comments.

var x = 1;
one(); // 10
two(); // 20
console.log(x); // 1

function one() {
  var x = 10;
  console.log(x);
}
function two() {
  var x = 20;
  console.log(x);
}
Enter fullscreen mode Exit fullscreen mode

The most important thing we have to remember here is that when functions look for variables they check their local memory environment first before checking their parents' memory environment. That is the reason why one() prints 10 and two() prints 20 although there is an x variable in their parent's environment with a value of 1.

How does the call stack work?

The reason why we jump to the call stack after talking about functions in the previous paragraph is because every time a function is invoked a local execution environment is created which means that the local execution environment is pushed into the call stack.

The snapshot below shows how the call stack works. The local and global memory is highlighted in orange and the call stack is highlighted in yellow. As you can see variable x is in the local variable which is where JS looks first before going on to check the global scope(its parent).

The anonymous highlighted in yellow is the global execution environment and one is the local execution environment which was created because function one was invoked in line 2. Once function one prints 10, it is popped off the call stack and function two will be pushed into the call stack.

If this does not make sense reviewing part 2 (JS Execution Context) of this series should help.
image

Top comments (0)