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.
[00:00] 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.
[00:13] 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.
[00:31] 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.
[00:41] 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.