Stop Using ‘var’ to Declare Variables in JavaScript
An introduction to `const` and `let`
We all start somewhere. I learned JavaScript declaring variables with the var keyword. It was simple and it worked, but I’ve changed.
If you write code like var x = 5 you need to stop. Well, I’ll be honest, you don’t have to, but you should.
We often think of programming languages as a set of rules etched in stone. The reality is that a programming language — like any spoken language — is ever-evolving.
I now use the keywords const and let to declare all my variables in JavaScript and so should you.
Let’s learn how and why.
Declaring True Constants
A variable, by name, intimates a changing value. While there’s not necessarily anything wrong with declaring and not touching a variable, if we’re trying to write code that makes semantic sense then we should distinguish between variables and constants.
A constant is the opposite of a variable, a declared value that does not change. Historically, to define a constant we used all capital letters, like the bright coloring on a toxic animal.
Instead of relying on convention, the introduction of the const keyword gives us an explicit option for declaring that which does not change.
To use the const keyword, simply swap it out with var and now that value cannot be modified.// the old way
// var sales_tax = 0.06;// the new way
const sales_tax = 0.06;sales_tax = 0.08; // "TypeError: Assignment to constant variable.
The implementation is simple, the rationale is simple. Using const is a no-brainer. But when is this appropriate?
Numeric ratios such as a tax rate or a conversion between units are easy pickings. The other place you’ll see const being used is declaring functions using arrow notation.const myFunction = (x,y) => {
// Do stuff
}myFunction(1,2)
Now your function cannot be overwritten.
Fixing JavaScript’s Quirky Scope
JavaScript suffered from a lack of scope clarity that often led to frustrations with development and troubleshooting. Here is a summary of the JS scope oddities:
- could use
vartwice with a variable (redeclaration) - top-level variables were global by default (global object)
- variables could be used before being declared (hoisting)
- variables in loops reused the same reference (closures)
Using let clarifies and solves many of these oddities. Let’s take a closer look.
Redeclaration
This one’s simple, you cannot redeclare a variable that was made with let.var x = 0;
let y = 0;var x = 1;
let y = 1; // "SyntaxError: Identifier 'y' has already been declared
Global Object
At the top level, variables declared with var are added to the global object as a property whereas let variables are not.var x = 0;
let y = 0;console.log(window.x); // 0
console.log(window.y); // undefined
Hoisting
Variables defined with let are only accessible inside their block-scope while var variables are hoisted to the function level.// Using var
console.log(i); // undefined
for(var i=0; i<4; i++) {
console.log(i);
}
console.log(i); // 4// Using let
console.log(j); // "ReferenceError: j is not defined
for(let j=0; j<4; j++) {
console.log(j);
}
console.log(j); // "ReferenceError: j is not defined
Closures
This one’s hard to understand if it’s a new concept, but a closure is a function that references a free variable.
When we have a closure with a var variable, the reference is remembered, which can be troublesome when inside a loop where that variable changes.var functions = [];for (var i = 0; i < 3; i++) {
functions[i] = () => { console.log(i); };
}
for (var j = 0; j < 3; j++) {
functions[j]();
}// 3 3 3
Using let, a new reference is created each time.var functions = [];
for (let i = 0; i < 3; i++) {
functions[i] = () => { console.log(i); };
}
for (var j = 0; j < 3; j++) {
functions[j]();
}// 0 1 2
Ultimately even if you aren’t 100% on these reasons and why they work the way they do, switching over to let will result in more explicit code that behaves consistently and will be easier to troubleshoot/maintain.
A Word of Caution
Although let and const should effectively replace the var keyword, life isn’t always so simple. Since these keywords were introduced in ECMAScript 2015 (ES6), if the platform you work on does not allow it then you’re out of luck. Additionally, you’ll want to make sure you take steps to ensure your code works across the browsers of your target audience.
Do you still find yourself using var? What’s stopping you from switching over to using const and let? Share your experiences below!