Skip to main content

JavaScript Immutability

5 minute read



In programming, when talking about immutability, there are some closely related words and their meanings that we should take in to account. There's immutable (of course), writable, and constant. So, let's have a look at these before diving into JavaScript specifics (Object.freeze() and Object.seal() methods).


Immutable

The definition of immutable is: not mutable; unchangeable; changeless. In object-oriented programming, an immutable object is defined as an object whose state cannot be modified after it is created. Immutability works on the value not the variable. Therefore, a variable can point to an immutable object then to another or even a mutable object throughout its life. However, the immutable object the variable originally pointed to still will remain unchanged. In most programming languages, including Java and JavaScript, a String object is immutable. For example:

    var name = "Chris"; //defining a string object
    name.toLowerCase(); //doesn't alter the original object, this call does nothing
    var lowerCaseName = name.toLowerCase(); //the method calls returns a new immutable object but does not change the original

    name = "Ryan"; //the original object does not change, only the variable points to a different object


Constant

The definition of constant is: not changing or varying; uniform; regular; invariable. In programming, a constant is defined as a variable that cannot be changed. Therefore, seemingly making it not a "variable". A constant can be seen as somewhat of the opposite of an immutable. An immutable cannot change, yet, a variable pointing to it can. A constant variable cannot change its value, yet, it is possible for parts of the value to change. In Java, you denote a variable or field as constant using the final keyword. In JavaScript (ECMAScript 6), you denote a variable or field as constant using the const keyword. For example:

    const num = 23; //variable num is a constant and its value will always be 23.
    const obj = {"key", "value"}; //obj value will always be this object
    obj = {"otherKey", "otherValue"}; //will not work, cannot change the value of obj
    obj.key = "otherValue"; //will work. obj value stays the same yet its objects values may change


Writable

The definition of writable is: capable of recording data. In object-oriented programming, writable refers to whether a property's value can change or not with an assignment operator. Usually, writable is a property itself which takes a boolean value. If true, the properties value can be changed (or written to), if false, the properties value cannot be changed. It's applied to a property in an object (which is basically a variable belonging to that object) and states whether its value can be changed. If set to false, that property becomes like a constant for the specific object and its value cannot be changed, making it immutable. Note, as stated before with immutable objects, being immutable doesn't mean part of the immutable objects values can't change. So, a property which is not writable can be seen like a combination of constant and immutable. This is useful when needed to create read-only properties. For example, in JavaScript you could do:

   Object.defineProperty(obj, "key", {writable: false});

Where, in the above code, obj refers to the object where you're adding the property, key defines the property name, and writable is set to false making it a read-only property.


Object.freeze()

The Object.freeze() method became available in ECMAScript 5.1 with some added functionality coming in ECMAScript 6 (freezing primitive values). This method prevents an object from being modified in any way including adding, deleting, or editing properties, making the object effectively immutable. How to use it:

    Object.freeze(obj);

The object entered as a parameter becomes immutable. Also, the method returns the immutable object, so if you needed to assign it to a variable you could. Note, that if a frozen objects property is an object, that objects values can still be changed. In this case, you would need to use a loop to go through all of the properties to make sure each of their properties are frozen too.


Object.seal()

The Object.seal() method, also added in ECMAScript 5.1, is very similar to the Object.freeze() method. The major difference is that Object.seal() allows its already existing properties to be edited. If a property is an object, its properties can still be edited after being frozen or sealed. However, if a property is a primitive, it can be edited or changed if it is sealed, but if it is frozen it may not be edited. The method is simply used like:

    Object.seal(obj);

The object entered as a parameter becomes sealed, meaning nothing can be added or removed from it. Also, it returns that same object if you would like to assign it to a variable.


Summary

Immutability is an important ability for object-oriented programming. It allows for the development of better applications and API's. Code becomes thread safe and less error prone. JavaScript provides, starting with ECMAScript 5.1, a couple of approaches for immutability. These approaches are the freeze() and seal() methods of Object. Also, we've seen approaches to providing similar concepts of immutability, such as, the const keyword and the writable property within the defineProperty() method of Object. This understanding should help us build better, safer, and more robust JavaScript applications and API's. If you found any errors in my code or writings, or have any input, please feel free to leave a comment! And, of course, for more detail on the subjects I recommend using Mozilla Developer Network (MDN). 

Comments

Popular posts from this blog

Face detection and live filters

Live video filters are becoming a popular trend fueled by Facebook (through their purchase of Msqrd) and Snapchat incorporating the features into their apps. These filters apply images or animations to your face using face tracking software. This technology has been around for awhile but is becoming increasingly more common due to the powerful CPU's that our mobile phones now have. Google provides an API that provides face tracking abilities through the Google Play Services library called Mobile Vision. I'm going to use their API to build a basic live filter app. The end result will look something like this:


    The bounding box wraps around the detected face and the sunglasses are the filter I chose (which is just a PNG image) which are drawn over the eyes. You could use any PNG image (with alpha for the background) you want, you will just have to adjust the layout according to where the image should be displayed. As you move your head, the box and sunglasses are redrawn…

Setting Up Connection Pooling With Elastic Beanstalk

Amazon's Elastic Beanstalk is a service which automatically scales your application when needed. It uses Amazon's Elastic Compute Cloud (EC2) instances as deployable containers which when your app requires more resources more containers will be deployed. This removes the need to manually configure your EC2 instance whenever you need more connections or resources and attempts to add simplicity to the maintenance aspect of your application. So, when you get more users of your app, your app will scale accordingly.

    Unfortunately, along with the ability to scale automatically, comes less control and configuration. Things you would normally have the ability to configure to your liking, such as your server, you no longer can. Amazon attempts to address this issue with configuration files. You can provide configuration files which can set up your server. These files are either written in JSON or the horrible format YAML. Though these files provide some level of control, you ca…

Android Guitar Tuner

Recently I created a guitar tuner application for Android that is written with pure Java (no C++ or NDK usage). The design was inspired by the Google Chrome team's guitar tuner web app using the WebAudio API. I wanted to code a version written natively for Android that didn't have to rely on a WebView, the WebAudio APIs, or server-side logic. Also, I wanted this application to be available to as many versions of Android as possible (whereas the WebAudio API may only be supported in more recent versions of WebView available only on newer flavors of Android). So, I coded it from scratch. I used a portion of the open source TarsosDSP project (their YIN algorithm) to help with the pitch detection.

    The application is available in the Google Play Store for Android: https://play.google.com/store/apps/details?id=com.chrynan.guitartuner. The project is completely open source and the code can be found on the GitHub repository: https://github.com/chRyNaN/Android-Guitar-Tuner. Fi…