Node.js Collection
Published in

Node.js Collection

What does const stand for in ES6?

If you come from a C-like programming language, you may wonder why the first ES6 JavaScript code is valid, but the second C program (as you well know) will make the compiler fail.

# JavaScript
const numbers = [1, 2, 3, 4, 6]
numbers[4] = 5
console.log(numbers[4]) // print 5
# C
const int numbers[] = {1, 2, 3, 4, 6};
numbers[4] = 5; // error: read-only variable is not assignable
printf("%d\n", numbers[4]);

The reason why is because in C, const defines a read-only variable that is not modifiable, whereas in JavaScript, it is not about value immutability. It doesn’t indicate that a variable’s value is constant or read-only. Instead, it creates an immutable binding (a read-only reference to the value) and guarantees that no reassignment will happen. With this being said, the following code will throw an error at run-time.

const numbers = [1, 2, 3, 4, 6]
numbers = [7, 8, 9, 10, 11] // error: assignment to constant variable

To understand the concept of variable better, let’s examine the following image where the generic relationship between a variable identifier (or variable name), its value, and the physical memory is being explained.

Variables and memory allocation.

As you can see from the schema, a variable identifier refers to a physical memory cell through an address (reference) in which the assigned value to the variable is stored. A read-only variable doesn’t allow its value to be changed. A read-only reference to the value simply doesn’t allow the variable identifier to be reassigned, but the value held by the identifier itself can still be changed. For instance, in JavaScript, when the value is an object, the object itself can be altered.

How to make a value immutable

Primitive datatypes are always immutable because of their nature. The following code snippet intuitively explains why.

# Example 1
const a = 10
a = a + 1 // error: assignment to constant variable
# Example 2
const isTrue = true
isTrue = false // error: assignment to constant variable
# Example 3
const sLower = 'hello world'
const sUpper = sLower.toUpperCase() // create a new string
console.log(sLower) // print hello world
console.log(sUpper) // print HELLO WORLD

To make an object’s values immutable, you can use Object.freeze(). However it only works on property-value pair objects, which means it won’t work with other objects such as Date, Map and Set.

# Example 4
const me = Object.freeze({name: “Jacopo”})
me.age = 28
console.log(me.age) // print undefined
# Example 5
const arr = Object.freeze([-1, 1, 2, 3])
arr[0] = 0
console.log(arr[0]) // print -1
# Example 6
const me = Object.freeze({
name: 'Jacopo',
pet: {
type: 'dog',
name: 'Spock'
}) = 'Rocky' = 'German Shepherd'
console.log( // print Rocky
console.log( // print German Shepherd

As you can see in the last example, nested objects within a frozen object can still be mutated. To make object values fully immutable, you may want to use a custom deepFreeze() method. Another option is to use Immutable.js, a library which simply doesn’t turn objects into immutables, but rather provides many Persistent Immutable data structures including List, Stack, Map, OrderedMap, Set, OrderedSet and Record.

var, let or const?

In ES6, developers should never use var to define a variable or a constant. In fact, it is now the weakest signal available when you define a variable in JavaScript.

A well-defined variable should not be used to represent multiple concepts. This ensures that the code is cleaner and more understandable. Since JavaScript const means that the identifier can’t be reassigned, it is preferable to use const for all the identifiers in the program that are not supposed to be reassigned. However, when the identifiers need to be reassigned, programmers should use let instead. This is generally the case for counters in a loop construct or values swap in algorithm subroutines.

Take home lesson

Recapping the insights: if you code with ES6, use const by default, don’t use var, and use let where rebinding is needed✌️️. If you have any questions on this or updates, please reach out to me on social at Jacopo Daeli.




Community-curated content for the millions of Node.js users.

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
Jacopo Daeli

Jacopo Daeli

I’m a Computer Scientist, Software Engineer and Hacker, passionate about web technologies with a vocation for writing beautiful and clean code.

More from Medium

“Flat” Promises for Reactive Code

3 Reasons Why TypeScript is Better Than JavaScript

Lazy Evaluation in JavaScript

Intuitive Code

An open Apple laptop, notebook, tea cup and saucer on a wooden table