var declarations are globally scoped or function scoped while let and const are block scoped. This means you can declare the a let or const with the same name inside an if statement and it will be self contained.
let a = "a";
const b = "b";
if(a == "a"){
let a = "aa";
const b = "bb";
console.log(a + " " + b);
}
console.log(a + " " + b);
The console would log “aa bb” followed by “a b”.
Let and const can’t be redeclared in the same scope, preventing the issue of accidentally changing another variable with the same name and breaking things.
const can’t have it’s value changed although if it’s an object, the properties of the object can be.
const name = {
first: "Mark",
last: "Wang"
}
name.last = "Wong";
console.log(name);
This would log out {first: ‘Mark’, last: ‘Wong’}
Leave a Reply