Execution of a JavaScript program, the temporal dead zone and JS functions

Photo by Clément Hélardot on Unsplash

Note: JavaScript is synchronous and single-threaded language, which means that it executes one command at a time in a certain order.

1. Execution of a JavaScript program

Whenever a JavaScript program is run an Execution Context (EC) is created (visualize it as a container), it contains 2 components:
1. Variable Environment (Memory): consists of key-value pairs (variable: value)
2. Thread of Execution (Code): in this, the code execution takes place.

Logical representation of Execution Context after Memory Creation Phase

2. Let, Const and the Temporal dead zone

Let and const declarations are hoisted;
What is hoisting?
Hoisting can be understood better now as we know about the memory creation phase that takes place during the creation of execution context.
Memory is allocated to all the variables and functions even before a single line of code is executed, and the initializations if any take place during the code execution phase. The following program explains this:

Both variables ‘a’ and ‘b’ are hoisted, but variable declared with ‘let’ gets inside a separate memory space
let a = 20
let a = 30
// SyntaxError: Identifier 'a' has already been declared
const a
a = 1000
console.log(a)
// SyntaxError: Missing initializer in const declaration
const a = 10
a = 20
// TypeError: Assignment to constant variable.

3. Functions

  1. Function Statement/Function declaration:
console.log(a) 
/* logs ƒ a(){
var v = 10;
console.log(v);
} */
a() // logs 10function a(){
var v = 10;
console.log(v);
}
console.log(v) // o/p: undefined v() 
// TypeError: v is not a function
var v = function () {
var a = 10;
console.log(a)
}
v() // logs 10
function(){
...
}
/* This code when run will give a SyntaxError, saying that function statements require a function name */
var v = function func(){
console.log('called')
}
v() // logs 'called'func()
// ReferenceError: func is not defined
var v = function func(){
console.log(func)
}
v()/* o/p: ƒ func(){
console.log(func)
}*/
function f1(parameter){
return function(){
parameter()
console.log('from returned function')
}
}
var v = f1(function(){
console.log('passed as an argument')
})
v()
/* o/p: passed as an argument
from the returned function */

Interested in web-app development and cloud computing domains

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store