Immutable Array Methods: How to Write Remarkably Clean JavaScript Code



In our guide to variable assignment and mutation in JavaScript, we covered the concepts of variable assignment and mutation, looking at issues with mutations and how to manage them. In this article, we’ll see how JavaScript makes life extra difficult for us by including array methods that mutate the original array as part of the language. But it’s not all doom and gloom. By the end of the article, we’ll have written some functions that fix these issues — and you’ll be able to start using these functions in your code today.

If you’d like to explore this topic in greater detail, or get up to speed with modern JavaScript, check out my new book Learn to Code with JavaScript.

Array Mutations in JavaScript

Arrays in JavaScript are just objects, which means they can be mutated. In fact, many of the built-in array methods will mutate the array itself. This can mean the golden rule from above gets broken, just by using one of the built-in methods.

Here’s an example showing how it can potentially cause some problems:

const numbers = [1,2,3];
const countdown = numbers.reverse();

This code looks fine. We have an array called numbers and we want another array called countdown that lists the numbers in reverse order. And it seems to work. If you check the value of the countdown variable, it’s what we expect:

countdown
<< [3,2,1]

But the unfortunate side effect of the operation is that the reverse() method has mutated the numbers array as well, which is not what we wanted at all:

numbers
<< [3,2,1]

Even worse, the two variables both reference the same array, so any changes that we subsequently make to one will affect the other. For example, if we use the Array.prototype.push() method to add a value of 0 to the end of the countdown array, it will do the same to the numbers array (because they’re both referencing the same array):

countdown.push(0)
<< 4
countdown
<< [3,2,1,0]
numbers
<< [3,2,1,0]

It’s these sort of side effects that can go unnoticed — especially in the depths of a large application — and cause some very hard to track bugs.

And reverse isn’t the only array method that causes this sort of mutation mischief. Here’s a list of array methods that mutate the array they’re called on:

Slightly confusingly, arrays also have some methods that don’t mutate the original array, but return a new array instead:

These methods will return a new array based on the operation they’ve carried out. For example, the map() method can be used to double all the numbers in an array:

const numbers = [1,2,3];
const evens = numbers.map(number => number * 2);
<< [2,4,6]

Now, if we check the numbers array, we can see that it hasn’t been affected by calling the method:

numbers
<< [1,2,3]

There doesn’t seem to be any reason for why some methods mutate the array and others don’t (although the trend with recent additions is to make them non-mutating), so it can be hard to remember which do which.

Ruby has a nice solution to this in the way it uses bang notation. Any method that causes a permanent change to the object calling it ends in a bang, so [1,2,3].reverse! will reverse the array, whereas [1,2,3].reverse will return a new array with the elements reversed.

Continue reading
Immutable Array Methods: How to Write Remarkably Clean JavaScript Code
on SitePoint.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Immutable Array Methods: How to Write Remarkably Clean JavaScript Code

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.