[JAVASCRIPT] What is the difference between let, var, const, and where to use it.
let /const
Scope: let and const have block scope which means they are accessible within the block in which they are declared
Reassignment: let can be reassigned with a new value but in terms of const it cannot be reassigned once declare
function letConstEx(){
let x = 5
const y =6
if(true){
let z = 6;
console.log(x)// able to get value of its block scope is start of the fucntion still end
console.log(y)
}
console.log(z) // ReferenceError: z is not defined as its block scope is if condition
}
letConstEx()
Var
Scope: It has a functional scope which means they are accessible within the function where they are declared
Reassignment: the Value of var can be declared again and again inside the same function.
function even() {
var x = 2; // declare inside a even function
var y = 3;
if(x ===2 ){
var x = 5// reassignment of var
console.log(x)// able to get the value
}
else{
console.log(y)
}
}
even()
In general, it's recommended to use const for values that are not meant to be reassigned, and let for values that are meant to change. var should be avoided in modern JavaScript.
I hope you found the blog useful. If so, please consider sharing it with your friends. If not, I would appreciate your feedback. You can also reach out to me on Twitter at @lalitaswal2, and I would be happy to hear your thoughts