DEV Community

Kenton Vizdos
Kenton Vizdos

Posted on • Originally published at blog.kentonvizdos.com on

let vs const vs var: when to use which

let vs const vs var: when to use which

Variable used to be the norm in JavaScript, but now there are better players on the playing field: let and const. The main difference? Scope.

See, scope is important in programming. In most cases, always using global variables isn't a great idea, but there are still some good uses for it if you look hard enough.

First, lets go over the similarities and differences between let and const. Mainly, both are locally scoped so:

const letsTest = () => {
    let x = 5;
}

letsTest();

console.log(x) // this fails.

But also, it is very useful in for loop scenarios:

var a = [];
(function () {
   'use strict';
   for (let i = 0; i < 5; i++) { // ***`let` works as expected***
     a.push( function() {return i;} );
   }
} ());
console.log(a.map( function(f) {return f();} ));

As expected, a now equals [0,1,2,3,4], however if you make a small change by changing let to var, you'll notice things start getting gross as it would return [5,5,5,5,5]

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Block_scope_with_let

As for a difference, const is a constant variable (woah), so it cannot be changed after initialization

const x = 5;
x = 1; // Fails.

Other than that, let and const are pretty much the same. Better than var. As of ES6, var hardly ever should be used.

While this is a short article, it is good to know the very small differences between the three. Best of luck with your variables!

Top comments (0)