Var VS Let VS Const
What is difference between var,let and const;
VAR
It is a keyword for variable declaration in javascript. It is function scoped means if you declared a variable inside a block of a function then it is scoped to whole function not just inside the block . It's available for whole function doesn't matter you are using it before declaration because of hoisting. like this one
function greeting(waves){
if(waves===true){
var greet= "Hello Champ!"
}
return greet;
}
but if you want access greet
before if block it is accessible which would have value undefined
because hoisting but what is hoisting ?
Hoisting
In hoisting if a variable is declared using var
keyword then it hosted on top of the function just variable declaration not the value of the variable.
like this one
function greeting(waves){
console.log(greet)
if(waves===true){
var greet= "Hello Champ!"
}
return greet;
}
greeting(false)
LET
It is also a keyword for variable declaration in javascript. But it is block scoped means its available for that block only not outside that block. like this one
function greeting(waves){
if(waves===true){
let greet= "Hello Champ!"
}
return greet;
}
greeting(false)
In this function if waves value is false then in that case it would give a error
Uncaught ReferenceError: greet is not defined
greet is only accessible in if block only not outside the block.
CONST
It is also a keyword for variable declaration but for constant
value. It is also block scoped. And it value assigned only once in block.
Thanks for reading. Feel free to correct.