1. Home
  2. >
  3. Differences between var, let and const?
3

Differences between var, let and const?
shantanu singh

The differences can be summarized in three points:

  1. Assignment: Both let and var can be re-assignmed. const cannot be re-assigned
  2. Hoisting: Variables declared using var are always hoised to the top of their respective scope, while variables declared using const and let are hoisted, but if you try to access them before they’re declared, you will get a ‘temporal dead zone’ error
  3. Scope: var is function-scoped, let and const are block-scoped

 

/**

HOISTING

*/
var x = "global scope";
function foo() {
  var x = "functional scope";
  console.log(x);
}
foo(); // "functional scope"
console.log(x); // "global scope"


// What if we were to drop the second var
var y = "global scope";
function bar() {
  y = "functional scope";
  console.log(y);
}
bar(); // "functional scope"
console.log(y); // "functional scope"


/**

SCOPE

*/
var a = 0; 
let b = 0;
const c = 0;
if (true) {
  var a = 1;
  let b = 1; 
  const c = 1;
}
console.log(a); // 1
console.log(b); // 0
console.log(c); // 0
# javascript# hoisting