DEV Community

Samaresh Das
Samaresh Das

Posted on

Stop memorizing JS — think in execution context

Forget remembering JavaScript syntax; it's a crutch.

What if I told you that the key to truly understanding JavaScript isn't memorizing endless functions and methods, but grasping how the code actually runs? This article is about shifting your focus from rote learning to thinking about JavaScript's execution context.

Every time your JavaScript code runs, the engine creates an "execution context." Think of it as a mini-environment where your code gets evaluated. There are two main types: the Global Execution Context (the default one for your entire script) and the Function Execution Context (created each time a function is called).

Within each context, two crucial things happen: the creation phase and the execution phase. During creation, the engine sets up the Variable Environment (where var, let, const, and function declarations are stored) and the this binding. It also creates the scope chain.

Then comes the execution phase, where the actual JavaScript code is run line by line. This is where let and const declarations are put into a "temporal dead zone" until their declaration is reached, while var variables are initialized with undefined.

Let's look at a simple example.

console.log(a); // undefined
var a = 10;
console.log(a); // 10

// sayHello(); // This would throw an error
// let sayHello = () => {
//   console.log("Hello!");
// };
Enter fullscreen mode Exit fullscreen mode

The first console.log(a) outputs undefined because var a is hoisted to the top of its scope and initialized with undefined during the creation phase, before the execution phase reaches var a = 10;. If a were declared with let or const, the first console.log would actually throw a ReferenceError because of the temporal dead zone.

Understanding execution context helps untangle confusing behavior, especially with asynchronous operations and closures. It's the "why" behind what your code is doing.

For me, this mindset shift was a game-changer. It's what allows me to build complex websites and apps as a freelancer. If you're ever looking for someone to build your next web project, you can check out my portfolio here: https://hire-sam.vercel.app/

The real superpower in JavaScript isn't memorization, it's understanding the runtime.

Follow for more dev content

Top comments (0)