The new ES6 variable declarations
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
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.
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;
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