How JavaScript Works: An Overview of JavaScript Engine, Heap, and Call Stack

Bipin Rajbhar - Apr 29 '20 - - Dev Community

Hello everyone 👋, I hope you are doing great.

So, today you are going to learn An Overview of JavaScript Engine, Heap, Call Stack 🧑‍💻.

Many JavaScript developers don't know how JavaScript works. If you are new to JavaScript 👶, then this article will help to learn how JavaScript works. If you are an experienced 👴, JavaScript developer hopefully, this article will be a good refresher for you.

⚙️ JavaScript Engine

The JavaScript engine is a program that executes your JavaScript code. A popular example of a JavaScript engine is Google's V8 engine.

⚙️ V8 Engine

The V8 engine is an open-source, high-performance JavaScript and Web Assembly engine written in C++. The V8 engine is used inside Google Chrome, Node.js, and electron, among others.

Overview of V8 Engine

The V8 engine has two main components

  • Heap is an unstructured memory that is used for memory allocation of the variables and the objects.
  • Call Stack is a LIFO data structure that is used for function calls that record where we are in the program.

🥞 Call Stack

JavaScript is a single-threaded programming language, which means it can do one thing at a time, and it has one Call Stack.

If you call a function, it's pushed on the top of the Call Stack, and when the function returns, it's popped from the top of the Call Stack.

Let's take an example.

Call Stack Visualization
call stack Visualization

Let's take another example that contains an error.

Call Stack Visualization
Call Stack Visualization

When the V8 engine encounters an error, it prints a stack trace. A stack trace is basically the state of the Call Stack.

Let's take another example that blows up the Call Stack 💥.

We can do this by using a recursive function.

Call Stack Visualization
call stack Visualization

A recursive function calls itself again and again. At some point in time, the number of function calls exceeds the actual size of the stack, and the browser detects this to take action by throwing an error.

I hope now you have a fair understanding of how JavaScript works.

In the next article, we will learn about Web APIs, Callback Queue, and Event Loop.

📚 Resources

What the heck is the event loop anyway? | Philip Roberts | JSConf EU

Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills 😊. You can follow me on Twitter if you’d like to be notified about new articles and resources.

. . . . . . . . . . . . . . . . . . . . . . . . .