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

Eric Damtoft
2 min readOct 25, 2019

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.

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…

--

--