OdeToCode IC Logo

Features Of ES6 Part 2 : const

Wednesday, August 6, 2014

The ES6 const keyword will give you what the keyword name implies – a read-only variable. Like let, a variable declared with const will have block scoping, and you cannot re-declare a const.

const MAX_BUNNIES = 3;

There is no requirement for a constant variable to use capital letters, that’s just a convention I like to follow.

The Significance of const

In a perfect world, all the JS runtimes would have a perfect implementation of const. Unfortunately, const is one of those keywords that has been around in some runtimes even before the keyword appeared in an official ECMAScript specification.

While most runtimes can agree that a const should be constant, existing implementations disagree on how to behave when code attempts to assign a new value to a constant. Should the assignment cause a runtime error? Should the assignment fail silently?

The ES6 specification says const should fail with a runtime error if a program tries to assign a new value to a constant, and constant declarations without an initializer should be a syntax error.

const MAX_SIZE = 10;

MAX_SIZE = 12; //SyntaxError 

I hope that it won’t take long for all the latest runtimes and browsers to straighten up and behave correctly. The current situation shouldn’t stop you from using const whenever possible because the keyword does have a few benefits.

1. const tells other programmers about the intended behavior of a variable, and this makes code easier to read.

2. const tells the runtime about the intended behavior of a variable, which can allow for small optimizations across time and space.

Coming up next: default parameters.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!