var, let and const

var, let and const

These keywords are used to declare the variable in javascript. before ES6 we could declare variables by using only the var keyword but in ES6 let and const are introduced these have distinct roles.

TDZ(Temporal Dead Zone) - it's the area before the declaration of variables that are declared with let and const.

The difference between let, var and const

var

Scope - The var keyword has functional and global scope.

redeclare - we can redeclare the variable by using the var keyword.

reassign - we can reassign values to the variable that are declared with the var keyword.

TDZ(Temporal Dead Zone) - There is no TDZ for the variable that is declared with the var keyword.

let

Scope - The let keyword has a block scope.

redeclare - we can't redeclare the variable by using the let keyword.

reassign - we can reassign values to the variables that are declared with the let keyword.

TDZ(Temporal Dead Zone) - TDZ is available for the variables declared with the let keyword.

const

it's used to declare constant values.

Scope - The const keyword has a block scope.

redeclare - we can't redeclare the variable by using the let keyword.

reassign - we can't reassign values to the variables that are declared with the const keyword.

TDZ(Temporal Dead Zone) - TDZ is available for the variables declared with the const keyword.

Lexical Scope - The ability of a function scope can access variables from the parent scope. in js function variables are lexically scoped they can be accessed from its parent where the function body is defined not where the function is called.

Example

console.log('line no 1', varName); // undefined
var varName = 10;
function b() {
    console.log('at line no 4', varName);
}
function fn() {
    console.log('at line no 7', varName); // undefined
    var varName = 20;
    b() // 10
    console.log('at line  no 10', varName) // 20
}
fn();
console.log('line no 1', varName); // undefined
var varName = 10;

function fn() {
    console.log('at line no 5', varName); // undefined
    var varName = 20;
    // suppose there is function where varName not defined
    function b() {
        console.log('at line no 9', varName);
    }
    b() // 20
    console.log('at line  no 12', varName) // 20
}
fn();

Hoisting

The default behavior of moving all the declarations at the top of the scope before code execution.

console.log('line no 1', varName); // undefined
var varName = 10;

Did you find this article valuable?

Support SAURABH TARAGI by becoming a sponsor. Any amount is appreciated!