Tag Archives: let

JavaScript ES6+: Which do you use var, let, or const?

Perhaps the most important thing you can learn to be a better coder is to keep things simple. In the context of identifiers, that means that a single identifier should only be used to represent a single concept.

`const` is a signal that the identifier won’t be reassigned.

`let`, is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it’s defined in, which is not always the entire containing function.

`var` is now the weakest signal available when you define a variable in JavaScript. The variable may or may not be reassigned, and the variable may or may not be used for an entire function, or just for the purpose of a block or loop.


With `let` and `const` in ES6, it’s no longer safe to check for an identifier’s existence using `typeof`:

function foo () {
typeof bar;
let bar = ‘baz’;
foo(); // ReferenceError: can't access lexical declaration
// `bar' before initialization