Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create an immutable List using Immutable.js

    Taylor BellTaylor Bell

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.