Difference between var,let and const in javascript

var,let and const in javascript

Use of var in javascript

This statement is used to declare function-scoped or globally-scoped variables. It optionally initializes a value. The var declaration occurs before the code is executed. The var begins with declarations and statements.

Examples

1. Declaration

var a=1;

var b;

console.log(a); //output: 1

console.log(b); // output:undefined

  1. Use in function

    function varTest(){

    var x=2;

    {

    var x=3 // same variable

    console.log(x)//output: 3

    }

    console.log(x) //output: 3

    }

Use of let in javascript

The let statement is used to declare block-scoped local variables. It also optionally initializes a value. It allows declaring variables limited to the scope of a block statement or expression. A let and const variable is said to be in the 'temporal danger zone' (TDZ) from the start of the code until the code execution reaches the line where the variable is declared and initialized. The let begins only with declarations, not statements.

Example

function letTest(){

let x=1;

{

let x=2; //different variable

console.log(x) //output: 2

}

console.log(x) // output: 1

}

Use of const in javascript

It creates block-scoped constants, much like the variables declared by the let keyword. The value of const cannot be reassigned and redeclared. It is compulsory to initialize const variables.

Example

function constTest(){

const num=7;

{

num=3;

console.log(num)// Invalid assignment

}

console.log(num) //output: 7

}