How JavaScript Works

In the last lesson, we learned the features of JavaScript. Now let us open the box and see what actually happens when you run JavaScript code.

Don't worry, we will keep it simple!

Step 1: The JavaScript Engine

A computer does not understand JavaScript directly. It only understands machine code, which is 0s and 1s.

So who translates our code? The JavaScript engine.

Every browser has its own engine:

  • V8 in Chrome and Edge (Node.js also uses V8)
  • SpiderMonkey in Firefox
  • JavaScriptCore in Safari

Think of the engine as a translator who converts your JavaScript into a language the computer understands.

Step 2: From Code to Action

When you run JavaScript, the engine works in three simple steps:

  1. Parsing: The engine reads your code and checks it for mistakes, like a teacher checking your answer sheet.
  2. Compiling: It converts your code into machine code. Modern engines do this just in time (JIT), right before running it, which makes it fast.
  3. Executing: The computer runs the machine code, and you see the result.

Step 3: One Task at a Time (Single-Threaded)

JavaScript is single-threaded. This means it does one thing at a time, in order.

Imagine a railway ticket counter with only one clerk. The clerk serves one person, then the next, then the next.

JavaScript keeps track of this work using the call stack. It is like a stack of plates: the last plate kept on top is the first one removed. When a function runs, it goes on the stack. When it finishes, it comes off.

Step 4: Handling Slow Tasks (The Event Loop)

But wait. If JavaScript does only one thing at a time, what happens with a slow task, like downloading data? Will everything stop?

No! This is where JavaScript becomes smart.

Slow tasks are handed over to a helper (the browser or Node.js). JavaScript continues with other work. When the slow task is done, its result waits in a line called the callback queue.

The event loop keeps checking: "Is the call stack empty?" When it is, the waiting task gets its turn.

It is like a restaurant. The waiter takes your order and gives it to the kitchen, then serves other tables. When your food is ready, he brings it to you. The waiter never stands still waiting.

See It in Action

Output:

1. Order placed
2. Serving other customers
3. Food is ready!

Notice that message 3 comes last, even though it was written in the middle. setTimeout is a slow task, so JavaScript gives it to the helper, continues with the next line, and prints message 3 after 2 seconds.

Key Takeaways

  • A JavaScript engine (like V8) converts your code into machine code.
  • The engine parses, compiles (JIT), and executes your code.
  • JavaScript is single-threaded and uses the call stack to do one task at a time.
  • Slow tasks are handled in the background, and the event loop brings their results back when the call stack is free.
  • This is why JavaScript can do one thing at a time without ever getting stuck waiting.