JavaScript is a high-level, interpreted (or JIT-compiled), and multi-paradigm language.
Every browser has an engine (Chrome has V8, Firefox has SpiderMonkey). The engine’s job is to take your code and turn it into machine code that the computer understands.
Everything in JavaScript happens inside an Execution Context. Think of it as a container that holds the variables, functions, and the value of this for the code currently running.
window object (in browsers) and the this keyword.This is the “Secret Sauce” of JavaScript. When you run code, the engine goes through it twice.
The engine scans the code for variable and function declarations.
undefined.The engine reads the code line-by-line and assigns actual values to the variables.
Hoisting is a result of the Memory Creation Phase. It allows you to use functions and variables before they are actually declared in the code.
var)JavaScript
console.log(greet); // Output: undefined
var greet = "Hello World";
console.log(greet); // Output: "Hello World"
Why? Because in the Memory Phase, greet was set to undefined.
JavaScript
sayHi(); // Output: "Hi there!"
function sayHi() {
console.log("Hi there!");
}
Why? Because the entire function body is stored in memory before the code runs.
Note:
letandconstare also hoisted, but they are stored in a “Temporal Dead Zone” (TDZ). You cannot access them until the line where they are defined, or you will get aReferenceError.
The Call Stack is how JavaScript keeps track of its place in a script that calls multiple functions. It follows the LIFO principle (Last In, First Out).
JavaScript
var n = 2;
function square(num) {
var ans = num * num;
return ans;
}
var square2 = square(n);
var square4 = square(4);
n: undefinedsquare: { … function code … }square2: undefinedsquare4: undefinedn becomes 2.square(n) is called. A New Execution Context is created for the function.ans is calculated and returned.square2 becomes 4.square4.