12. MEDIUM | Code Execution in JavaScript
This article will talk about how a javascript code is executed behind the scenes.
Code execution in javascript happens in two phases:-
1. Memory creation phase
JS engine reads all the variable names and function declarations and allocates memory to them. It finds variable names by searching
var,letorconstkeywords.
varvariables are initialized with a defaultundefinedvalue.
letandconstvariables are not initialized with any default value. Instead, they remain in an "uninitialized" state.
2. Code execution phase
JS engine executes the code line-by-line.
It assigns value to the variables.
If there is a function call, JS engine enters to its local execution context.
Let's understand this with the help of examples:-
EXAMPLE 1
var firstName = 'Shubham';
let lastName = 'Agrawal';
let age = 30;
const yearOfBirth = 1995;
let userIntro = 'My name is' + ' ' + firstName + ' ' + lastName + '.'
Temporal Dead Zone (TDZ)
The Temporal Dead Zone (TDZ) is a period within the scope of let and const variables where those variables cannot be accessed until they are initialized with a value. Attempting to access a variable in the TDZ will result in a ReferenceError.
You can see line by line javascript code execution in the Sources tab of dev tools.
EXAMPLE 2
var firstName = 'Shubham';
let lastName = 'Agrawal';
const age = 30;
function sayHi() {
let a = 14;
const b = 12;
var c = 20;
console.log(a, b, c);
}
sayHi();
EXAMPLE 3
var firstName = 'Shubham';
let lastName = 'Agrawal';
const age = 30;
function sayHi() {
let a = 14;
const b = 12;
var c = 20;
add(2, 5);
console.log(a, b, c);
}
function add(x, y) {
return x + y
}
sayHi();
Call Stack
It is a mechanism in the JavaScript engine that manages the execution of function calls in your code. It operates on a Last-In, First-Out (LIFO) principle.
When the program starts, the global execution context (denoted by
anonymous) is the first item pushed onto the stack. It is the last one to be removed when all code has finished running.Each time a function is called, a record containing the function's details (arguments, local variables, where to return) is created. This record is called a stack frame and is pushed onto the top of the call stack.
When a function completes its execution and returns a value, its frame is "popped" off the top of the stack.
Happy reading!

