DEV Community

loading...
Cover image for A Simple Formula For When To Use Let, Const, and Var
DealerOn Dev

A Simple Formula For When To Use Let, Const, and Var

edamtoft profile image Eric Damtoft ・2 min read

The new ES6 variable declarations let and const have been available in major browsers for several years, but when to use each still causes a bit of confusion. Although everyone has a different style and preferences, the above flowchart is how I choose which one to use. There are more in-depth guides to the exact differences between each, but this is meant to be a simplified way of how to choose without getting too deep into the nuances of the javascript runtime.

Flowchart

var was the original way to declare a variable. For a while, it had to be used for any non-transpiled code because of compatibility concerns. By now, all major browsers and even IE11 support let and const. The var keyword declares a mutable reference to a value, but it is not block scoped. As someone who mostly writes c#, this means that it will occasionally cause some unexpected behavior. See this stack overflow response for some examples. It also permits bad practices like referencing a variable before it's been declared.

let and const give a more predictable experience and both generally act like you would expect a variable declaration to. The only significant difference is whether you can reassign the value. In my experience, reassignments can often be refactored to be immutable references. This means they never change state which improves clarity. Consider the following:

let value = readInput();

value = value.toUpperCase();

return value;

The variable value is reassigned to hold different values representing different states. At a glance, you can't tell what state the variable holds, which makes complex logic significantly more difficult to comprehend. Instead, by using the const keyword, we can ensure that the variable will only ever hold the state it's initially assigned. You'll also note that our variable names can become much more descriptive when one variable doesn't need to hold multiple states. Reassigned variables often are named generic terms like "output", "value", etc.

const input = readInput();

const upperCasedInput = input.toUpperCase();

return upperCasedInput; // this line is self-explanatory

In general, I find that const is always my preferred way to declare a variable. Sometimes, you can't avoid reassignments, so I fall back to let if there's no way to refactor away from it. I don't even consider using var except when working with legacy code.

Cover Image by Irvan Smith on Unsplash

Discussion (0)

pic
Editor guide