When to Use var or let or const

Hero image for When to Use var or let or const. Image by Maximalfocus.
Hero image for 'When to Use var or let or const.' Image by Maximalfocus.

With the introduction of ES6 back in 2015, a lot of new major features were introduced to the JavaScript language. Two of those features are the let keyword, and the const keyword. They give us two new ways to declare variables in JavaScript but why would we need them? Isn't var good enough already?

As you might expect, these weren't changes without cause; var, let, and const all have their own specific use cases where they make the most sense. Let's take a look at a few of the differences between these keywords below, starting with the one we're probably all most familiar with: var.


The var Keyword

Variables declared with var are unconcerned with scoping, outside of function scoping, which affects all of the variable keywords. Regardless of whether you declare a variable with let, const, or var, anything declared within a function is inaccessible outside of that function. With var, variables are accessible outside of the blocks that they're declared within. For instance:

{  var foo = 'bar';  console.log(foo);  //=> 'bar'}console.log(foo);//=> 'bar'

Both of these console logs will write bar to the console, because block scope doesn't matter to variables declared with var. This could seem useful in that it allows you to share values across blocks, but in reality, it leads to messy and unmaintainable situations in bigger applications where scope really beings to matter.

Widespread use of var leads to a lot of variables being stored in the global scope, and being declared and redeclared repeatedly, which can lead to a confusing experience for devs working on the code.

For an example, let's take an oldschool for loop:

var i = 500;for (var i = 0; i < 1000; i++) {}console.log(i);//=> 1000

When run, the console will output 1000 here, rather than the 500 you might (reasonably) expect. This might not seem immediately like a huge issue especially in an abstract fourline example but in a full web app it might have some undesired consequences; redeclaring variables and ignoring block scoping can be an issue, especially when using singleletter variables for simple things like i to represent iteration indexes

Paying more attention to the scopes that your variables are accessible in, and being strict with them, can help you keep things neat when working on large, complex sites or web apps and cut down on that spaghetti code. This is where the real magic of let and const become apparent.


The let Keyword

The let keyword is a step towards stricter treatment of variables, allowing for variables declared via let to be reassigned but not redeclared, and making variables take notice of block scoping. If we take our earlier for loop example again, we can immediately see the difference:

let i = 500;for (var i = 0; i < 1000; i++) {}console.log(i);//=> 500

This time using let instead of var console returns 500. This is because the i within the for loop (which previously redeclared i in the var example) is by block scoping and cannot affect the global scope.

However, there is another key benefit to bear in mind here, too; let prevents redeclaration.

var foo = 'bar';var foo = 'foo';console.log(foo);//=> 'foo'let bar = 'bar';let bar = 'foo';console.log(bar);//=> will not run

Here, foo will be logged into the console as foo. However, the program won't allow the second block to run because bar is declared twice using let. Instead, you'll get a nice red error in the console:

Uncaught SyntaxError: Identifier 'bar' has already been declared

This is helpful because it enforces some of the issues that we would historically have experienced with var inside of global scope. It keeps variable declarations neat and prevents the confusion that redeclaration might cause in a codebase by providing a verbose error to help you track down your original declaration.

It should be said here: the other key difference between let and const (which I will talk about below) is that let can be reassigned a new value very simply:

let lorem = 'ipsum';lorem = 'dolor';console.log(lorem);//=> 'dolor'

Here, the console will log out dolor because although lorem was originally assigned to ipsum, it was subsequently reassigned to dolor.

So, let's finish up by taking a look at const.


The const Keyword

The const keyword is reasonably selfexplanatory; variables declared using const should be constant throughout your apps. The value of a variable declared with const shouldn't change, and the const keyword enforces that by throwing an error if you attempt to redeclare it or reassign it.

const foo = 'bar';foo = 'foo';console.log(foo);//=> will not runconst bar = 'foo';const bar = 'bar';console.log(bar);//=> also will not run

In both these cases, you will receive the same error in the console because you're trying to reassign a variable declared with const:

Uncaught TypeError: Assignment to constant variable

As we discussed above, this strict type enforcement helps avoid issues you may have historically come across when dealing with var variables.

It is however worth bearing in mind that although a const variable cannot be reassigned, some object properties and array data stored within a const can be. Ideally, though you should intentionally choose to use const in situations where you do not want or need the variable to change.


The Wrap‑Up

var, let, and const all accomplish essentially the same job; creating and declaring variables. However, let and const accomplish this in a much more structured and responsible way, allowing for clearer code and easier management of that code, by limiting scopes and preventing redeclaration. There might be times when you want to affect the global scope by using var, but by and large, it makes much more sense to be mindful and intentional with your usage of scopes when working with variables, even if just for the sake of the developer who comes to the code after you...!


Categories:

  1. Development
  2. ES6
  3. Front‑End Development
  4. JavaScript