The Difference Between let and var in JavaScript

Feb 24, 2021

In JavaScript, you can use let or var to declare mutable variables. A variable with the let keyword will only be used within the block it is declared and not affect variables used in nested blocks, like if statements and for loops, or outside the block. Below is an example:

let x = 1;
if (x === 1) {
  let x = 2;
  if (x === 2) {
    let x = 3;
    x; // 3
  }
  x; // 2
}
x; // 1

The other option is var. The var keyword's reach can be function-scoped or globally-scoped. var variables declared in functions will not bleed into other functions, but will into nested blocks, like if statements and for loops.

var x = 1;
if (x === 1) {
  var x = 2;
  if (x === 2) {
    var x = 3;
    x; // 3
  }
  x; // 3
}
x; // 3

Hoisting

Another difference between let and var is you can use a variable declared with var before the actual var statement. This is because JavaScript "hoists" all var declaration to the start of the function call. This is a common source of confusion, which is one of the reasons why we recommend using let instead of var.

function test() {
  console.log(x); // undefined
  console.log(y); // "ReferenceError: Cannot access 'y' before initialization"
  var x = 3;
  let y = 3;
}

test();

let declarations are hoisted too, but you get a ReferenceError if you try to access a variable declared with let before the actual declaration statement runs. That is why the error message is "Cannot access 'y' before initialization", as opposed to "y is not defined", which is what JavaScript would throw if you didn't declare y at all.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!