What is difference between var and let in JavaScript?

Please explain this difference through examples.

 

Var:---- 

The var statement declares a function-scoped or globally-scoped variable, 

optionally initializing it to a value.

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 2


var declarations, wherever they occur, are processed before any code is executed.

This is called hoisting, and is discussed further below.

 

The scope of a variable declared with var is its current execution context and closures thereof,

which is either the enclosing function and functions declared within it, or, for variables declared

outside any function, global. Duplicate variable declarations using var will not trigger an error,

even in strict mode, and the variable will not lose its value, unless another assignment is performed.

 

'use strict';
function foo() {
  var x = 1;
  function bar() {
    var y = 2;
    console.log(x); // 1 (function `bar` closes over `x`)
    console.log(y); // 2 (`y` is in scope)
  }
  bar();
  console.log(x); // 1 (`x` is in scope)
  console.log(y); // ReferenceError in strict mode, `y` is scoped to `bar`
}

foo();

Variables declared using var are created before any code is executed in a process

known as hoisting. Their initial value is undefined.

 

Let:---  

The let statement declares a block-scoped local variable, optionally initializing it to a value.

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1

let allows you to declare variables that are limited to the scope of a block statement,

or expression on which it is used, unlike the var keyword, which defines a variable

globally, or locally to an entire function regardless of block scope. The other difference

between var and let is that the latter is initialized to a value only when a parser evaluates it.

 

Just like const the let does not create properties of the window object when declared

globally (in the top-most scope).