1) Difference between var, let, and const?
VAR
var msg = "Hello world"; if(true){ console.log("1 "+ msg) } console.log("2 "+ msg) // output // 1 Hello world // 2 Hellow world
“var” is globally accessible, even if it is inside the scope like below example
if(true){ var msg = "Hello world"; console.log("1 "+ msg) } console.log("2 "+ msg) // output // 1 Hello world // 2 Hellow world
Above both “var” declaration gives output same.
LET
But “let” variable type will not accessible from one to another.
if(true){ let msg = "Hello world"; console.log("1 "+ msg) } console.log("2 "+ msg) // msg is not defined
Here the above example will give the output “msg is not defined”.
console.log("2 "+ msg) ^ ReferenceError: msg is not defined at Object.<anonymous>
CONST
const msg = "Hello"; if(true){ msg = msg + " world"; console.log("1 "+ msg) } console.log("2 "+ msg)
const stands for constant.
The constant variable will not able to modify the values. So, it throws an error “type error” like below.
msg = msg + " world"; ^ TypeError: Assignment to constant variable. at Object.<anonymous>
var | Globally Accessable on both inside and outside of scope |
let | Not Globally Accessable. It is accessable only in inside of scope |
const | Not Globally Accessable on both inside and outside of scope. Once declare and assign the variable will not able to modify the values. |
Check the next questions to crack the interviews.