DEV Community

kim-jos
kim-jos

Posted on • Edited on

2 1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay