Skip to content

JavaScript immutable arrays | Example code

  • by

JavaScript primitives data types like string, number, and boolean are immutable by default, they cannot be altered. But JavaScript objects and arrays are not immutable by default, because they are only references.

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.

JavaScript immutable arrays

Simple example code goes through some operations that will help us to keep also objects and arrays immutable.

You can create an immutable copy of an array using Array.slice() with no arguments, or with the Array.from() method. It’s considered a best practice to do so before manipulating an array.

<!DOCTYPE html>
    let sandwiches = ['turkey', 'tuna', 'ham', 'pb&j'];
    // Create an immutable copy
    let evenMoreSandwiches = Array.from(sandwiches);

    // Add a few sandwiches
    sandwiches.push('italian', 'new blt');





JavaScript immutable array

You can use the spread operator for this

let moreSandwiches = [...sandwiches];
let moreLunch = {...lunch};

Cloning an array of primitive data types.

const sourceArray = [1,2,3];
const clonedArray = [...sourceArray];
// or you can do
const clonedArray = sourceArray.slice(0);

Do comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *