Difference between var, let and const in JavaScript

JavaScript originally had only one variable type var. JavaScript introduced new variable declarations in ES6.

  • let
  • const

Now we have variable declarations let, var and const. The inevitable question is when to use what? Before we answer this question, let's understand the scope of a variable?

  • function scope : When the variable is only available to use inside the function it is declared inside. Outside the scope, it will result in a reference error.

    function functionname() {
    const a = "1";
    console.log(a); // 1
    }
    functionname();
    console.log(a);
    // ReferenceError: a is not defined
    
  • block scope : A block of code is between two curly brackets. Outside the scope, it will result in a reference error.

    {
    const a = "1";
    console.log(a); // 1
    }
    // All the lines between the curly brackets form one block.
    console.log(a);
    // ReferenceError: a is not defined
    

    var

    The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. - mdn

var varname3 = "3";
if (true) {
  var varname = "1";
}
console.log(varname); // globally-scoped
// 1
function funcname2() {
  console.log(varname3);
}
funcname2();
// 3
function funcname() {
  var varname2 = "2";
  console.log(varname2);  // function-scoped
// 2
}
var name = "4";
var name = "5";
console.log(name); // 5
console.log(varname2);
// ReferenceError: varname2 is not defined
  • The console log in function works as expected except for the one outside it.
  • console.log(varname); isn't block-scoped so it's available globally.
  • The caveat with var is it can be redeclared.
  • This resulted in a lot of state errors viz why developers abandoned it.

    let and const

  • The let declaration declares a block-scoped local variable, optionally initializing it to a value.
  • Constants are block-scoped, much like variables declared using the let keyword.
  • The value of a constant can't be changed through reassignment.
  • Both can't be redeclared.
    // code for let;
    let letvar = "1";
    let letvar = "2";
    console.log(letvar);
    // SyntaxError: Identifier 'letvar' has already been declared
    let letvar1 = 4;
    letvar1 = "5"; // reassignment
    console.log(letvar1); // 5
    if (true) {
    let letvar2 = "6";
    }
    console.log(letvar2); // block scope
    // ReferenceError: letvar2 is not defined
    const a = "1";
    a = "b";
    console.log(a);
    // TypeError: Assignment to constant variable.
    

    gotchas for const

  • Only arrays and objects can be amended after declaring the variable with const as long as they are not reassigned.
const arr = [1, 2, 3, 4];
const obj = { a: 1 };
arr.push(5);
console.log(arr); // [ 1, 2, 3, 4, 5 ]
obj.a = 4;
obj.b = 6;
console.log(obj); // { a: 4, b: 6 }