Modern JavaScript syntax – ES6 const variables

Introduction

ES6 brought lots of new features. Among them is support for constants. Instead of using var while declaring variables, you are now free to choose between const and let.

In this tutorial I will focus primarily on const and its “immutability” quirks, while let will be tackled in the following one. Without further ado, let’s start it off by going through the handful of examples.

Assumptions

  • Familiarity with Codepen, JSFiddle or JSBin
  • Familiarity with Browser Developer Tools

Example I – Primitive

As you see, you must assign an initial value to const variable. Additionally, you cannot redeclare it, nor assign a new value, unless it’s in different scope. Similar rules apply to variables of type string, integer, float and so on, as well as to variables holding a function expressions. (const f = function() { return 'sth'; })

Example II – Array

As you see, you cannot reassign anything to PLANETS nor redeclare it, pretty similar as for primitives. However you can modify, add or delete elements inside this array, which may seems a bit awkward at first.

Example III – Object

Like arrays, you cannot reassign anything to PERSON object nor redeclare it, but you can freely modify, add or delete any properties inside this object.

If you truly need an immutable object or array, you may use Object.freeze as shown below.

Keep in mind though that freeze is a shallow operation, so you need to repeat it in all of your child objects and arrays.

Alternatively, you could use Object.seal that allows changes of the existing properties, but forbids to add new ones.

ES5 equivalent

Once you run this, you actually won’t be able to undo this action.

  • it’s forbidden to redefine window.PI using Object.defineProperty again
  • it’s impossible to delete it via delete window.PI

It turns out you can only refresh your page to get this value cleaned up. Feel free to learn more about Object.defineProperty or leave a comment if you found a way…

Summary

Variables defined as constants work predictable and well with primitives as strings, integers or floats. However they should be used with caution when applied to arrays or objects. People mostly assume const variables as immutable, but in the world of JavaScript the reality is different.

There is lots of documents, tutorials, videos and books related to ES6 constants, including the following:

If you stumbled across any other interesting materials, please let me know in the comments below.

I tend to declare const variables using capital letters. Additionally, I default to const every time I declare a new variable. If I need to reassign it later on, I simply change it to let, therefore trying to stay away from var variables.

Code samples

 


If you enjoyed this post, then make sure you subscribe to my Newsletter