const, let and var

Part of the Series:
Javascript

JavaScript is an amazing and powerful programming language, it allows us to create amazing websites, applications, and way more things than we can imagine in today’s world.

In this first article, we’re going to start talking about variables and constants definitions, specifically, we’re going to cover the next items for all of them:

  • Definition
  • How to use them
  • Differences between const, let and var
  • When to use them
  • Examples

const

Allows us to define constants (basically variables whose values can not change over time), constants are block-scoped meaning that they are isolated by expressions that use curly brackets such as conditionals and loops.

For example, the code below will end up in an error saying that, MARS_GRAVITY is not defined

if (true) {
    const MARS_GRAVITY = '3.711 m/s²';
}
console.log(MARS_GRAVITY);

this happens because the constant was defined inside the conditional block, which means that we can only access it from within its scope, so just move the console.log inside the conditional and that’s it.

How to use

const MY_NAME = 'Enmanuel';

When to use: Use not only when knowing that a type of data remains constant but also when you’re not certain whether data will need to change or not, why? because using it as default helps you realize if a value mutates or not and diminishes the number of mutations, if you never had the need to change it, you know it is a constant.

Important Note: The reserved word const only makes the variable itself immutable which means that if we define an object or an array using it we could still modify the object’s or array’s properties and values, for example:

Let’s say we have the EARTH constant which is assigned an object like so:

const EARTH = { type: 'Planet' };

If we now try to add a property to EARTH like:

EARTH = { type: "Planet", water: true; }

We’ll get an error with something like, Uncaught TypeError: Assignment to constant variable, excellent, just what we wanted right?, hmm… but wait, what happens if instead, we do something like:

EARTH.water = false;

Ha!, now we don’t have any more water in our planet EARTH and we’re all gonna die because of it, this behavior occurs because what we’re actually changing is the object’s property, we’re not changing the variable itself, this same principle can be applied to arrays so be aware next time, because we can’t live without water.

let

We use let to declare variables that can change over time in our application, let is a block-scoped declaration as well as const.

When to use: As stated previously in const’s definition one implementation that is recommended and commonly used is to start declaring all your variables with const and if you realize later that one value needs to change during development, you change that declaration to use let, so the general rule would be to use const over let.

Example of use:

let names = 'Steve';
console.log(names); // Prints Steve

names = 'Tony';
console.log(names); // prints Tony

Important note: You can declare a let or const variable only once, if you do it again you’ll get an error, for example, based on the code above if you re-assign a value to names using the let reserved word like this:

let names = 'Steve';
let names = 'Tony';

You will get an error saying that 'names' has already been declared

var

It’s another way of declaring variables but this time function-scoped variables rather than block-scoped ones, this means that variables defined with var only respect the scopes of the functions in which they’re declared so if you declare a variable of this type inside a block like an if () { ... } conditional or a for() { ... } loop the variable will be declared outside of their inner scope and the value will be available in the whole function, for this reason since let came out it’s always recommended to use let instead of var, this being said, here a simple example for var:

function favoriteAnimal(person) {
    if (person === 'Jon') {
        var animal = 'direwolf';
    }

    console.log(animal);
}

The function favoriteAnimal simply logs the favorite type of animal for Jon, note how the animal variable is declared inside the if block but the console.log is executed outside of it and it can still access it without errors. In the other hand if you substitute the code above to use let instead, you’ll see how it will throw an error saying animal is not defined because it’s being scoped to the if block rather than the function.

Ok devs that's it for this article, I hope I was able to help you understand this topic a little more, if that was the case I invite you to share the article, it's very appreciated, see you in the next one.

Want to leave a comment? Do it on twitter

Found something to fix in the article? Edit it and send a Pull Request on GitHub!

Want to be the first to receive our cool updates?

Other Articles
June 04, 20199 min read

Code quality and web performance, the myths, the do's and the don'ts

April 22, 20197 min read

Avoid recomputing heavy tasks by leveraging memoization in javascript