var:
- hoisted (always declared at top of scope, global if none)
- function scope
let:
- block scope
- not redeclarable
const:
- block scope
- not reassignable
- not redeclarable
Note: Although it may seem like these hold only semantic meaning, using the
appropriate keywords helps the JS engines' compiler to decide on what to optimize.
`const` is a signal that the identifier won't be reassigned.
`let` is a signal that the variable may be reassigned, such as a counter in a
loop, or a value swap in an algorithm.
It also signals that the variable will be used only in the block it's defined
in, which is not always the entire containing function.
The difference is that with const you can only only assign a value to a variable
once, but with let it allows you to reassign after it has been assigned.
let = 10 // accessable only in defined scope
var = 10 // accessable in the function it is declared in (global variable in a function)
// var is a function scope ***
if(true){
var varVariable = 'This is var';
var varVariable = 'This is var again';
}
console.log(varVariable); // This is var again
// let is a block scope ***
if(true){
let letVariable = 'This is let';
let letVariable = 'This is let again';
// let variable can't re-define but we can re-assign value
console.log(letVariable); // let letVariable = 'This is let again';^SyntaxError: Identifier 'letVariable' has already been declared
}
console.log(letVariable); //ReferenceError: letVariable is not defined
// const variable can't re-define and re-assign value
// const is a block scope ***
if(true){
const constVarible = {
name: 'JavaScript',
age: '25 years',
};
constVarible.name = 'JS';
console.log(constVarible) // {name: 'JS',age: '25 years'} <= we can update const variable declared object
}