workabout

What is the difference between let and var?

You can list out the differences in a tabular format

var

  • It is been available from the beginning of JavaScript

  • Variables will be hoisted

  • It has a function scope

let

  • Introduced as part of ES6

  • It has a block scope

  • Hoisted but not initialized

Let's take an example to see the difference,

function userDetails(username) {

if(username) {

console.log(salary); // undefined(due to hoisting)

console.log(age); // error: age is not defined

let age = 30;

var salary = 10000;

}

console.log(salary); //10000 (accessible to due function scope)

console.log(age); //error: age is not defined(due to block scope)}