No fluff lets get directly into it !

var vs let vs const

Declaration

  1. var : Can be re-declared even after declaring it once !
  2. let : Cannot be re-declared ! Only one declaration per block !
  3. const : Same as let !

Mutability

  1. var : Mutable. Means will let you change values of variables,
  2. let : Mutable. Same as var will let you change values of variables.
  3. const : Immutable. Won’t let you change values of variables declared using const !

Scopes

  1. var: Function Scoped !
function scopeOfVar(){
    var x = 8;
    console.log(x);
}
scopeOfVar();

console.log(x); //ReferenceError: x is not defined

x is defined inside the function, hoisted to the top of the scope (the function in this case) and is not accessible outside of the function.

BUT….

for(var x = 0; x <= 3; x++){
    console.log(x);
}

console.log("x after loop: ", x);

Loops wont create a specific scope for var variables therefore its hoisted to the top of the global scope in this case and is accessible even outside the for loop !

  1. let : Block Scoped !
{
    let x = 3;
    console.log(x);
}

console.log(x); //ReferenceError: x is not defined

Here I defined a blank scope and declared x using let, since let is block scoped it will only be accessible inside that block ! And this applies for loops too…

for(let x = 0; x <= 3; x++){
    console.log(x);
}

console.log("x after loop: ", x); //ReferenceError: x is not defined

Its only limited to the scope of the particular block where its defined !

  1. const: Block Scoped !
{
    const x = 3;
    console.log(x);
}

console.log(x); //ReferenceError: x is not defined

Literally the same concept as let ! The only difference is of mutability !

const x = 15;
x = 79; //TypeError: Assignment to constant variable.

That’s it ! You cannot change the value assigned to x at initialization !


Check Quirky JavaScript Here : Quirky JavaScript