loading...

var, let, or const in Javascript ES6+??

christinamcmahon profile image Christina ・2 min read

In order to keep code clean and purposeful in Javascript, it is necessary to understand the differences between each of the identifiers. Being able to determine when a particular identifier is most appropriate can be a little tricky so here is a quick guide that should clear things up for you.

Var (don't use it)

As a general rule, avoid using var. var declarations are either globally or functionally scoped. They can also be re-declared and updated. The weakness here is that you could accidentally redeclare a var without any error, leading to a buggy program. The only place I might use var is when testing code in the console.

Let

let is block scoped and can be reassigned but not re-declared. It’s perfect for a loop counter, or a value swap in an algorithm. Since it’s block scoped, the variable will only be used in the block (the code wrapped in {}'s) it’s defined in, which is not always the entire containing function.

Const (a good default)

Similar to let, const declarations are also block scoped. What sets const apart is that it cannot be reassigned or re-declared. This means that every const declaration must be initialized at the time of declaration.

Summary

Scope is the most significant difference between the old-fashioned var and the modern let/const. To demonstrate the differences in scope:

if (true) {
  var foo = 'hello!';
  let bar = 'hi there!';
  const baz = 'howdy!';

  console.log(foo); // 'hello!';
  console.log(bar); // 'hi there!';
  console.log(baz); // 'howdy!';
}

console.log(foo); // 'hello!';
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
keyword scope reassignable?
var function yes
let block yes
const block no

Your go-to identifier in Javascript should be const. However, if you know or think you’ll need to reassign it (in a for-loop, switch statement, or in algorithm swapping, for example), use let.

Posted on Jul 2 by:

Discussion

markdown guide