Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1046 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Create an immutable List using Immutable.js

0:59 JavaScript lesson by

In this lesson we'll look at some of the differences between standard JavaScript Arrays and Immutable Lists. We'll create Immutable.JS Lists from scratch, as well as by converting regular Arrays. We will also compare and contrast the push and concat methods between both types of collection.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this lesson we'll look at some of the differences between standard JavaScript Arrays and Immutable Lists. We'll create Immutable.JS Lists from scratch, as well as by converting regular Arrays. We will also compare and contrast the push and concat methods between both types of collection.

We'll start by creating a regular JavaScript array. To do the same thing with immutable.js, we'll write, "let list = immutable.List()", and then pass array in. An immutable list has push and concat methods.

To add the number four to our regular array, we'll type array.push(4), and our console log confirms four is at the end. Let's do "list.push(4)." Notice that our log hasn't changed. Since immutable.js data structures can't be changed in place, we need to reassign the variable to push an item, so we just throw list equals in front.

Methods like concat, that return a new iterable, will behave the same between our standard array and our immutable list. As a side note, in this example, we're using an array which is an iterable object.

In JavaScript, a string is also an iterable object, so if we were to pass "word" into our list creation, we end up with each character instead of the string. To create a list of noniterable values, immutable has a .of() method. Now, we have a one item list with "word" in it.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?