A guide to var, let and const in JavaScript

MustSeeMelons
Nov 26, 2019 · 4 min read

Introduction

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:

// 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:

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:

console.log(x);

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:

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

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

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:

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.

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:

  • block scope
  • don’t allow re-declarations
  • are not hoisted

Meaning that we get the predictable behavior of other languages:

// 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.

// TypeError: Assignment to constant variable.

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

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:

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

Conclusion

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

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store