[go: up one dir, main page]

0% found this document useful (0 votes)
2 views1 page

Immutable Arrays and Objects in JavaScript, The Native Way

The document discusses the concept of immutability in JavaScript, particularly focusing on arrays and objects. It provides examples of how to replace mutable operations with immutable alternatives using methods like spread syntax and slice. The tutorial covers various array methods (push, pop, unshift, splice, sort, reverse) and object property manipulation (adding, modifying, removing) in an immutable way.

Uploaded by

priyanshrajput01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Immutable Arrays and Objects in JavaScript, The Native Way

The document discusses the concept of immutability in JavaScript, particularly focusing on arrays and objects. It provides examples of how to replace mutable operations with immutable alternatives using methods like spread syntax and slice. The tutorial covers various array methods (push, pop, unshift, splice, sort, reverse) and object property manipulation (adding, modifying, removing) in an immutable way.

Uploaded by

priyanshrajput01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

ALEX DEVERO BLOG Menu

Learn about
development, and
programming,
especially in
JavaScript, TypeScript
and React, and design.

Immutable Arrays and


Objects in JavaScript,
the Native Way

Ta b l e of C o n t e n t s [ hide ]

The idea of writing immutable


JavaScript is becoming more and more
popular. Primitive data types in
JavaScript are immutable by default.
Arrays and objects are not. This tutorial
will show you how to replace mutable
operations with arrays and objects with
their immutable alternatives.

Arrays
Arrays are one of the most frequently
used data structures in JavaScript. There
are many built-in methods we can use
when we work with them. The problem,
when it comes to immutability, is that
many of these methods are mutable by
nature. Using these methods means
changing the original data.

These mutable methods are push(),


pop(), splice(), shift(), unshift(),
reverse() and sort(). Fortunately,
there are alternatives we can use to
replace these methods if we want to
keep our JavaScript code immutable.
Let’s take a look at them.

Push

The push() method allows us to add a


new item at the end of existing array.
We can achieve the same result while
keeping our data immutable using
spread syntax. All we have to do is to
create new empty array, spread the
original, and add any item we want to
add. If we want to add multiple, we can.

// Mutable way:
const mutableArray = ['Apple', 'Netfli
// Add item at the end:
mutableArray.push('Amazon', 'Uber')

console.log(mutableArray)
// Output:
// [ 'Apple', 'Netflix', 'Microsoft',

// Immutable way:
const immutableArray = ['Apple', 'Netf
// Add item at the end:
const newArray = [...immutableArray, '

console.log(immutableArray)
// Output:
// [ 'Apple', 'Netflix', 'Microsoft' ]
console.log(newArray)
// Output:
// [ 'Apple', 'Netflix', 'Microsoft',

Unshift

Similar method to push() is


unshift(). The difference between
these two is that instead of adding new
item at the end of the array, unshift()
adds the item at the beginning. It
inserts the item as the first. The
immutable approach is similar to
push(), except that we have to reverse
the order of spread and new items.

// Mutable way:
const mutableArray = ['Apple', 'Netfli
// Add item at the beginning:
mutableArray.unshift('Amazon', 'Uber')

console.log(mutableArray)
// Output:
// [ 'Amazon', 'Uber', 'Apple', 'Netfl

Get guides and tutorials about modern


// Immutable way:
JavaScript, design, programming
const immutableArray = ['Apple', 'Netf
Email address Subscribe
// Add item at the beginning:
const newArray = ['Amazon', 'Uber', ..

console.log(immutableArray)
// Output:
// [ 'Apple', 'Netflix', 'Microsoft' ]
console.log(newArray)
// Output:
// [ 'Amazon', 'Uber', 'Apple', 'Netfl

Pop

The pop() method does two things.


First, it removes the last item from an
array. Second, it returns the removed
item. When it removes the item it
changes the original array. This happens
even if you try to assign the result of
this operation to a variable. We can do
both in immutable fashion.

When we want to get the last element of


an array, we can use indices. We take the
length property of an array, subtract 1
and the result is the last item. If we also
want to get the array, any items that
precede the last, we can use slice()
method.

// Mutable way:
const mutableArray = ['Apple', 'Netfli
// Get the last item:
const lastItem = mutableArray.pop()

console.log(lastItem)
// Output:
// 'Microsoft'

console.log(mutableArray)
// Output:
// [ 'Apple', 'Netflix' ]

// Immutable way:
const immutableArray = ['Apple', 'Netf

// Get the last item:


const lastItem = immutableArray[immuta
// Get the rest of the array:
const restOfArray = immutableArray.sli

console.log(immutableArray)
// Output:
// ['Apple', 'Netflix', 'Microsoft']

console.log(lastItem)
// Output:
// 'Microsoft'
console.log(restOfArray)
// Output:
// [ 'Apple', 'Netflix' ]

Shift

A reversed alternative to pop() is


shift(). This method also removes an
item from an array, but it removes it
from the beginning. It also changes the
original and returns the removed item.
Immutable alternative is similar to
pop(). The difference here is two-fold.

First, to get the first item in the array


we can use 0 as the index. For slice(),
and getting the rest of an array, we can
say that we want everything except the
first item.

// Mutable way:
const mutableArray = ['Apple', 'Netfli
// Get the first item:
const firstItem = mutableArray.shift()

console.log(firstItem)
// Output:
// 'Apple'

console.log(mutableArray)
// Output:
// [ 'Netflix', 'Microsoft' ]

// Immutable way:
const immutableArray = ['Apple', 'Netf

// Get the first item:


const firstItem = immutableArray[0]
// Get the rest of the array:
const restOfArray = immutableArray.sli

console.log(immutableArray)
// Output:
// ['Apple', 'Netflix', 'Microsoft']

console.log(firstItem)
// Output:
// 'Apple'
console.log(restOfArray)
// Output:
// [ 'Netflix', 'Microsoft' ]

Splice

The splice() method is handy when we


want to add, remove or replace items
in/from an array. We can achieve the
same in immutable fashion using
combination of spread syntax and
slice(). First, we create a new array.
Next, we use spread to copy the
original. After that, we use slice() to
keep what we want.

// Mutable way:
const mutableArray = ['Apple', 'Netfli
// Replace the 2nd item with two new i
mutableArray.splice(1, 1, 'Uber', 'Ama

console.log(mutableArray)
// Output:
// [ 'Apple', 'Uber', 'Amazon', 'Micro

// Immutable way:
const immutableArray = ['Apple', 'Netf

// Replace the 2nd item with two new i


const newArray = [
...immutableArray.slice(0, 1),
...['Uber', 'Amazon'],
...immutableArray.slice(2)
]

console.log(immutableArray)
// Output:
// ['Apple', 'Netflix', 'Microsoft']

console.log(newArray)
// Output:
// [ 'Apple', 'Uber', 'Amazon', 'Micro

Sort

The sort() method makes it very easy


to sort any array. By default, it sorts
item in an ascending order. However, we
can also provide custom sorting
function to sort the array in any way we
want. If we want to sort some array
while keeping it immutable, we don’t
have to re-invent the wheel.

We can still use the sort() method, but


in combination with spread syntax. The
spread syntax will help us copy the
original array. We can then take the
copy and sort it in any way we want.
This change will leave the original array
untouched.

// Mutable way:
const mutableArray = ['Microsoft', 'Ap
// Sort the array:
mutableArray.sort()

console.log(mutableArray)
// Output:
// [ 'Apple', 'Microsoft', 'Netflix' ]

// Immutable way:
const immutableArray = ['Microsoft', '

// Sort the array:


const newArray = [...immutableArray].s

console.log(immutableArray)
// Output:
// [ 'Microsoft', 'Apple', 'Netflix' ]

console.log(newArray)
// Output:
// [ 'Apple', 'Microsoft', 'Netflix' ]

Reverse

The reverse() is an alternative to


sort() that helps reverse the order of
items in an array. Just like the sort(), it
does so by changing the original array.
When we combine this method with
spread syntax, we can create a copy of
the array and apply reverse() to the
copy, leaving the original untouched.

// Mutable way:
const mutableArray = ['Apple', 'Micros
// Reverse the array:
mutableArray.reverse()

console.log(mutableArray)
// Output:
// [ 'Uber', 'Amazon', 'Netflix', 'Mic

// Immutable way:
const immutableArray = ['Apple', 'Micr

// Reverse the array:


const newArray = [...immutableArray].r

console.log(immutableArray)
// Output:
// [ 'Apple', 'Microsoft', 'Netflix',

console.log(newArray)
// Output:
// [ 'Uber', 'Amazon', 'Netflix', 'Mic

Objects
Objects are just as popular in JavaScript
as arrays, if not even more. Just like
arrays, objects are also by default
mutable. When we create an object, we
can add new properties or remove
existing at any time. There are ways we
can ensure this never happens by
freezing or sealing objects.

However, what if we actually want to


change an object, add or remove
properties, in immutable way? We can
do both.

Adding properties

When we want to add properties while


keeping our objects immutable we can
use the spread syntax. With spread, we
can create a clone of an object and
spread it into a new object. Then, we can
add any addition properties we want.

// Mutable way:
const person = {
firstName: 'Lori',
lastName: 'Robinson',
email: 'lori.robinson@example.com'
}

// Add properties:
person.birthday = '3/2/1993'
person.phoneNumber = '(094)-230-2145'

console.log(person)
// Output:
// {
// firstName: 'Lori',
// lastName: 'Robinson',
// email: 'lori.robinson@example.com
// birthday: '3/2/1993',
// phoneNumber: '(094)-230-2145'
// }

// Immutable way:
const person = {
firstName: 'Lori',
lastName: 'Robinson',
email: 'lori.robinson@example.com'
}

// Add properties:
const newPerson = {
...person,
birthday: '3/2/1993',
phoneNumber: '(094)-230-2145',
}

console.log(person)
// Output:
// {
// firstName: 'Lori',
// lastName: 'Robinson',
// email: 'lori.robinson@example.com
// }

console.log(newPerson)
// Output:
// {
// firstName: 'Lori',
// lastName: 'Robinson',
// email: 'lori.robinson@example.com
// birthday: '3/2/1993',
// phoneNumber: '(094)-230-2145'
// }

Modifying existing property


values

We can use the same approach also


when we want to change existing
property values. First, we create a new
object. Next, we spread the original
object into the new object. Finally, we
add any key-value pairs we want to
change. When some property already
exists, its value will be overwritten by
the new value.

// Mutable way:
const person = {
firstName: 'Lori',
lastName: 'Robinson',
email: 'lori.robinson@example.com'
phoneNumber: '(476)-632-5186',
}

// Add properties:
person.firstName = 'Nicholas'
person.lastName = 'Clark'
person.email = 'nicholas.clark@example

console.log(person)
// Output:
// {
// firstName: 'Nicholas',
// lastName: 'Clark',
// email: 'nicholas.clark@example.co
// phoneNumber: '(476)-632-5186'
// }

// Immutable way:
const person = {
firstName: 'Lori',
lastName: 'Robinson',
email: 'lori.robinson@example.com'
phoneNumber: '(476)-632-5186',
}

// Add properties:
const newPerson = {
...person,
firstName: 'Nicholas',
lastName: 'Clark',
email: 'nicholas.clark@example.com'
}

console.log(person)
// Output:
// {
// firstName: 'Lori',
// lastName: 'Robinson',
// email: 'lori.robinson@example.com
// phoneNumber: '(476)-632-5186'
// }

console.log(newPerson)
// Output:
// {
// firstName: 'Nicholas',
// lastName: 'Clark',
// email: 'nicholas.clark@example.co
// phoneNumber: '(476)-632-5186'
// }

Removing properties

When we want to remove some object


property, one option that will do the job
is the delete operator. We can do the
same in an immutable way using
destructuring assignment and spread
syntax. With destructuring assignment,
we can extract object properties one by
one.

After that, we can use the spread


syntax to get an object that contains the
rest of properties that remained.

// Mutable way:
const person = {
firstName: 'Lori',
lastName: 'Robinson',
email: 'lori.robinson@example.com'
phoneNumber: '(476)-632-5186',
}

// Remove properties
delete person.email
delete person.phoneNumber

console.log(person)
// Output:
// {
// firstName: 'Lori',
// lastName: 'Robinson'
// }

// Immutable way:
const person = {
firstName: 'Lori',
lastName: 'Robinson',
email: 'lori.robinson@example.com'
phoneNumber: '(476)-632-5186',

You might also like