Skip to main content

Command Palette

Search for a command to run...

The Engine Room: JavaScript Internals and Memory

Updated
8 min read
The Engine Room: JavaScript Internals and Memory

If you think your attention span is cooked because of Instagram Reels, imagine being the JavaScript Engine.

You’re basically a head chef in a high-speed restaurant where the customers (users) expect their food the second they think of it. To keep up, the engine doesn't just follow a recipe; it’s doing a hundred things behind the scenes that you never see. It’s predicting what you’ll order next, prepping ingredients in a "storage room" (Memory), and even translating the menu from a foreign language on the fly (JIT Compilation).

But here’s the kicker: if you label your ingredients wrong—like using those "gentleman’s agreement" underscores or messy objects—the chef gets confused, trips over the kitchen rug, and your app goes from "Gordon Ramsay fast" to "frozen microwave dinner slow."

Today, we’re going behind the kitchen door. We’re going to see why JS isn’t just Java’s little brother, how it stores your data in "Stacks" and "Heaps," and why your code actually runs the way it does.

1. The Translation: How JS Actually Runs

If the computer is the "Kitchen," JavaScript code is a recipe written in a language the equipment doesn't actually speak. To get the stove to heat up, we need a translator.

The "Pre-Game": Parsing (Reading the Ticket)

Before the chef even touches a pan, they have to read the order. In V8 (Chrome/Node), this is Parsing.

  • Lexical Analysis: The engine breaks your code into "tokens" (e.g., let, x, =, 5).

  • The AST (Abstract Syntax Tree): It builds a giant skeleton of your code’s logic. If you missed a closing bracket }, the Parser is the one who screams "Syntax Error!" and stops the show before it even starts.

The Old Way: The Slow-Reading Chef

Back in the day, JavaScript was a pure interpreter. The engine would read Line 1, tell the CPU to do it, then read Line 2, and so on.

  • The Good: It starts cooking the second you hand it the recipe.

  • The Bad: If the recipe says "Stir the soup 1,000 times," the interpreter reads that instruction 1,000 separate times. It’s like a chef who re-reads the manual every time they rotate the spoon.

The Modern Way: JIT (Just-In-Time) Compilation

Modern engines are like a high-performance relay race. They don't just "interpret" anymore; they use a hybrid called JIT.

  1. Ignition (The Interpreter): It takes that AST (skeleton) and turns it into Bytecode. It starts cooking immediately so the user isn't staring at a blank screen. It’s fast to start, but the execution is "just okay."

  2. The Profiler (The Spy): While Ignition is running, a "Profiler" watches for Hot code—functions you run over and over.

  3. TurboFan (The Optimizing Compiler): Once code is "Hot," TurboFan takes it and turns it into Machine Code (1s and 0s). This version runs at blistering speed.

The Secret Sauce: Speculative Optimization TurboFan is a gambler. It assumes that if you’ve called a function with two numbers 1,000 times, you’ll do it again. It strips away all the "safety checks" (like checking if the input is a string) to make the code run at maximum speed.

De-optimization: The "Oh Crap" Moment

JavaScript is dynamic, so you can betray TurboFan’s trust. If, on the 1,001st call, you suddenly pass a String instead of an Integer, TurboFan realizes its optimized machine code is now wrong.

It performs a De-optimization (De-opt). It throws away the "Turbo" code and kicks the execution back down to the slow-but-safe Ignition interpreter. This is the "Slow Lane." If your code constantly switches types, the engine spends all its time compiling and de-optimizing instead of actually running your app.

2. The Marketing Scam: JS vs. Java

As I broke down in my previous blog about why JS exists (Click here to read), the name "JavaScript" was a 1995 marketing stunt to hitch a ride on the Java hype train. But under the hood, they have totally different philosophies.

The Architect (Java) vs. The Athlete (JS)

Java is "Ahead-of-Time" (AOT): Java is like a rigid architect. Before the "house" is ever built, the developer has to run a separate command (javac) to turn the code into Bytecode.

  • The Catch: Every error must be fixed before the program can even start.

  • The Benefit: By the time the user runs it, the engine has a clear, locked-in plan. It doesn't have to "guess" anything while running.

JavaScript is "Just-In-Time" (JIT): JS is like a parkour athlete. There is no pre-build step. You send the raw recipe (text file) to the browser, and the engine has to parse, interpret, and compile it while the user is watching.

  • The Catch: The engine has to handle errors and type changes on the fly.

  • The Benefit: It’s incredibly flexible and starts instantly.

3. The "Morning Prep": How JS Sets the Table

Before the first customer walks in (before the code runs), the kitchen staff has to perform a two-phase routine. This is what developers call the Execution Context.

Phase 1: The Setup (Memory Creation)

Imagine the staff arriving at 8 AM. They don’t start cooking yet. Instead, they walk around and put labeled bins on the counter.

  • They put out a bin for "Burgers," a bin for "Fries," and a bin for "Soda."

  • Hoisting: Even though there is no food in the bins yet, the labels are already there. This is why you can sometimes mention a variable in your code before you define it—the engine already "reserved" the spot.

  • The "Empty Bin" (Undefined): At this stage, every bin is empty. If you try to grab a burger now, you get undefined. The engine knows you will have burgers, but it hasn't made them yet.

Phase 2: The Service (Execution Phase)

Now the clock hits 11 AM. The engine goes back to Line 1 and actually starts cooking. It goes line-by-line and fills those bins with real food (values).

4. The Counter vs. The Walk-in Freezer (Stack vs. Heap)

Where does the engine store your data? It depends on how big it is.

The Front Counter (The Stack)

This is for the small, quick stuff like a single "Salt Packet" or a "Straw." In JS, these are Primitives (Numbers, Strings, Booleans).

  • It’s right in front of you.

  • It’s super fast to grab.

  • When you "copy" a variable here, you are literally handing someone a second salt packet. They are separate.

The Walk-in Freezer (The Heap)

This is for the big, messy stuff like a "Crate of 500 Patties" (Objects and Arrays).

  • You can't fit a whole crate on the front counter. So, you keep the crate in the back freezer and keep a Small Slip of Paper (a Reference) on the counter that says "Crate #5."

  • The Reference Problem: If you give your friend a copy of that slip of paper, and they go to the freezer and take out 10 patties, the crate is now different for you too. You are both looking at the same crate. This is why changing an object in JS can accidentally change it everywhere else.So for this part we use the concept of shallow and deep copies which i would cover in upcoming blogs.

Memory Management in JavaScript - GeeksforGeeks

5. Null vs. Undefined: The "Empty" Truth

In our burger joint, these both mean "nothing," but for different reasons:

  • undefined (The Engine's Default)

    • What it is: A placeholder the engine uses during the "Morning Prep."

    • Memory impact: It’s a primitive value stored in the Stack. It basically means: "The bin is labeled, but the truck hasn't delivered the food yet."

    • Behind the scenes: If you don't assign a value, the engine does it for you. It’s like a default setting.

  • null (The Chef's Choice)

    • What it is: An intentional assignment by the developer.

    • Memory impact: This is where it gets weird. In JS, typeof null is "object". Even though it means "empty," the engine treats it as a reference to "nothing."

    • Why use it? If you have a huge crate in the Heap (Freezer) and you're done with it, you set that variable to null. This tells the "Cleaning Crew" (the Garbage Collector) that they can throw that heavy crate away to free up space.

6. The Underscore Mystery: Does _var change anything?

You might see developers using underscores like _privateVariable. Let’s set the record straight: The JS Engine does not care about the underscore.

To the engine's memory, _secret and secret are exactly the same. It parses the underscore just like any other letter. It doesn't magically hide the variable or change how it's stored in the Stack or Heap.

The catch: The underscore is a "Gentleman’s Agreement." It's a signal to other humans saying, "Hey, don't touch this." But as far as the "Chef" (the engine) is concerned, it's just another label on a bin. The performance only drops if you add that variable dynamically later on, not because of the name itself!

Key Takeaways (The Cheat Sheet)

  • The Translator (JIT): JS is translated into a "Fast Version" while you run it. The engine memorizes your "Hot" functions to cook them faster next time.

  • The Trap (De-optimization): If you tell the engine "I only use numbers" and then suddenly throw in a string, the engine gets confused and kicks you into the Slow Lane.

  • The Setup (Hoisting): The engine knows which "bins" (variables) you have before it starts cooking. If you grab one too early, you get undefined.

  • The Storage (Stack vs. Heap): Small stuff goes on the Stack (Counter). Big stuff goes in the Heap (Freezer). If you give a friend the key to your freezer, you're both touching the same food!

  • The Underscore Myth: _private is just a name. The engine doesn't treat it differently; only humans do.

What's Next?

Now that we know how the engine stores things in the Stack and the Heap, we need to look at what it's actually storing.

In the next part of this series, we’re going to look at Data Types. We’ll see why some data is "Simple" (Primitives) and why others are "Complicated" (Non-Primitives)—and how this choice determines if your app runs like a Ferrari or a tricycle.

Stay tuned!

JS Under the Hood: The Engine Room

Part 2 of 24

Ever wondered why your code actually runs? We’re going beyond the syntax to explore the V8 engine, memory management, and the "magic" that happens between your keyboard and the screen. Just deep dives.

Up next

Understanding Variables and Data Types in JavaScript

Imagine you are moving into a new house You have a lot of stuff—books, clothes, kitchen gadgets. To keep things organized, you put them in boxes and put a label on each box. So in programming the box