A guide to var, let and const in JavaScript

Nov 26, 2019 · 4 min read


There are three ways to declare a variable in Javascript:var , let and const — but why? To understand this, we should first take a quick look at the history of the language.

A very brief history lesson

The year is 1995, he web is completely static, every single interaction requires a whole page reload. Computers are at best sporting Pentium II processors with, at best, a max clock speed of 450Mhz, single core.

Java applets have just appeared and they seem like the way to go, but they require a lot of know-how to get the best results.

Netscape, a company that created one of the first browsers, decided that the web needed a simpler language, to do things like DOM manipulation, animations and general interactivity — to be used by lower tier programmers and designers.

Time was of the essence, the language was created in only six months, taking influences from Scheme, Self, and making it look like Java. It was simple, dynamic, easy to pick up and did its job well for its purposes.

With this in mind, lets move to the topic at hand..

Here comes var

The historical way of declaring variables seems innocent enough at first glance, like any other language, but when you start using it, sooner or later, you will bump into situations which will make you scratch your head:

for(var i=0; i<5; i++) {
setTimeout(() => {
}, 100);
// The output is 5, 5, 5, 5, 5

This behavior occurs because var is function scoped if declared inside a function, or global otherwise. In this case — it is global, if we want to make it so that every timeout gets its own value, we have to put it in a closure:

for(var i=0; i<5; i++) {
((i) => {
setTimeout(() => {
}, 100);

We create a new function and execute it immediately, passing the current value of i as a parameter. As a number is a primitive, the new function gets a copy of that value and we get the expected result, though a bit messy looking syntax wise.

There is more where this came from:

var x = 4;
var x = 5;
var x = 7;

var x = 10;

What will be the output? It will be 10 , as there is no block scope, just function scope.

We can even redeclare variables if we wish to:

var x = 5;
var x = 6;
console.log(x); // The output is 6

You can even not declare a variable, this will make it global and potentially overwrite something:

function func() {
y = 1;
func();console.log(y); // The output is: 1

These var statements are executed before any code is run, which leads to a behavior called hoisting , which means moving all the declarations to the top:

var tongueBender = "She sells seashells by the sea shore";

The output will be undefined , because only the declaration is moved up, the assignment stays where it is.

In newer versions of Javascript (starting from ECMAScript version 5), you can execute it with use strict , which will not allow using undeclared variables, but will still hoist and allow you to re-declare variables. It does other things as well, like not allowing to write to non-writable globals and throws errors instead of being silent in certain scenarios, full description can be found here.

"use strict"
fancyNumber = 42; // ReferenceError: fancyNumber is not defined

Going with the times

With all these quirks to look out for, two new ways of declaring variables came along in ECMAScript version 5: let and const — which made the life of a Javascript developer much more pleasant.

Variables declared or initialized with these keywords have:

Meaning that we get the predictable behavior of other languages:

for(let i=0; i<5; i++) {
// The output is: 0, 1, 2, 3, 4let x = 5;
let x = 6;
// SyntaxError: Identifier 'x' has already been declaredlet y = 4;
let y = 5;
let y = 7;
console.log(y) // The output is: 4

The const keyword, as the name implies, declares a constant, meaning its value cannot be changed later on.

const a = 4;
a = 5;
// TypeError: Assignment to constant variable.

One thing to keep in mind though is when working with objects:

const obj = {};
obj.a = 5; // Will work just fine
obj = {}; // TypeError

You can still modify the object, which is declared const as its still the same object. Properties can be made constant as well, if Object.defineProperty is used:

const obj = {};Object.defineProperty(obj, "a", {
value: 4,
writable: false,
obj.a = "5"console.log(obj); // The output is: {}

If use strict was set to this snippet, a type error would have been raised: TypeError: Cannot assign to read only property ‘a’ of object


Java applets are long gone by now and Javascript can now be used for far more thing that ever could have been imagined, thankfully, over time its shortcomings have been addressed and new features are still coming, private class fields anyone?

So, what should be used to declare a variable? The answer to this question is simple — if you can, always use const , let otherwise. By using const the codebase becomes more predictable and can even lead to performance gains through compiler optimizations (this is true in other languages as well).

Never use var , unless you like to live dangerously. Strict mode is preferred as well.

I’d recommend reading the full history of Javascript here, it is an very interesting read. Makes you wonder what is there to come :)

JavaScript in Plain English

Learn the web's most important programming language.


Written by

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade