Categories

What is difference between var let and const in Javascript

 var – Global scope when var variable is declared outside a function. It means that if you write following code 

if(true){

    var x = 30

}

console.log(x)

In console it will print 30 so it means x has a global scope because even though it is declared inside a if condition and inside brackets it can be accessed outside the brackets.

if(true){

    let  y = 30

}

console.log(y)

If I run the above code I will get error because let is a block scoped surrounded by {} If it is declared inside a bracket it can be accessed only inside the bracket and if it is declared outside the bracket it can be accessed anywhere and becomes a global variable

Both let and var declared inside a function are available only inside that function.

if(true){

    const  z = 30

}

console.log(z)



const – const is also a scope variable type just like let but only difference is const variable can not be changed as it is constant.

var type of variable can be initialized first and declared later but it is not possible with let and const

t=10

var t;

console.log(t) // will print 10 and no error 

adbanner