Joel's dev blog

Difference among const, let, var

October 01, 2017

2 min read

var

Varaiable declaration

var foo = 'bar1';
var foo = 'bar2';

makes no error.

Hoisting

console.log(foo); // undefined
var foo;

Hoisting works for var.

Scope For var, it’s a function scope.

function test(){
  var foo = 'bar1';
  cosole.log(foo); // bar1
  if (true) {
    var foo = 'bar2';
    console.log(foo); // bar2
  }
  console.log(foo); // foo outside changed to bar2. Means foo outside the if statement and foo inside it are the same variables. 
}

let and const

Variable declaration

let foo = "test";
let foo = "test2";

makes an error.

Hoisting

console.log(foo);
// Error: Uncaught ReferenceError: foo is not defined
let foo;

No hoisting for let and const.

Scope Block-scope for let and const.

let foo = 'bar1';
console.log(foo); // bar1
if (true) {
  let foo = 'bar2';
  console.log(foo) // bar2
}
console.log(foo); // bar1

let vs const

It’s all about immutability.

let test = 1
test = 2 // possible

const test2 = 1
test = 2 // impossible

and const should always be assigned a value when it is declared:

const abc = "abc" // correct
const fgh;
fgh = "fgh"; // incorrect. Cannot happen 

Sources


Written by Joel Mun. Joel likes Rust, GoLang, Typescript, Wasm and more. He also loves to enlarge the boundaries of his knowledge, mainly by reading books and watching lectures on Youtube. Guitar and piano are necessities at his home.

© Joel Mun 2024