Difference between var, let and const

Posted on

in

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

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

July 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
293031