Difference Between let and var in JavaScript

var

Variables declared by 'var' are available throughout the function in which they’re declared.

Example

function scope_var() {
  var x = 10;

  if (true) {
    var x = 20;
    console.log(x); // output: 20
  }

  console.log(x); // output: 20
}

Here, In scope_var(), one x variable is used throughout the function, even though an x variable is declared in two different places with different values.

let

Variables declared by 'let' are only available inside the block where they’re defined.

Example

function scope_let() {
  let x = 10;

  if (true) {
    let x = 20;
    console.log(x); // output: 20
  }

  console.log(x); // output: 10
}

Here, In scope_let(), two distinct x variables are used – one appears in the main function body and another in the if block

Note. At a global level, let does not create a property on the global object when working outside of function bodies, whereas var does.

Example

// Global variables

var x = 10;
let y = 20;

console.log(this.x); // output: 10

console.log(this.y); // output: undefined