Why would you need constants when you have closures?

Why use closures?

Saying that inability to declare constant variables is as wrong as not remembering that you can write closures. There are some exercises and approach to create immutable values with closures in JavaScript. It can be easily forgotten when writing lots of typical Object Oriented code.

Test Field

Assume we have a web page and our script in header:

First let's write simple code, case where you would like to insert only const before variable:

But there is an evil ad or something that can mess everything up!

And it breaks our code!

Let's make closure

We will make function that encloses variable and gives us access to it:

Does the evil ad can change it?

Nope, success, but... it's not very efficient

Closure creating an object

Let's call closure once and then use created object.

Here we can preview where closured variable are stored and what evil ad tries to do:

Works! It has it's own scope and doesn't pollute with any global variables.

But it's not immutable

Value can't be changed from outside but one change from inside results in disaster.


JavaScript allows freezing object properties, consider following changes:

And it's results

Sweet, happy debugging! Better let know that something is frozen. 'use strict' does it!

Will break if anyone tries to change frozen object. It's Immutable!

One last assumption

We have nice function to create objects. What happens when the evil ad will be annoying enough to reassign it? Frankly, we can't do much. Even Math functions can be reassigned.

Which reminds me of:

Code examples from this post are at github


Popular Posts