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. 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 keep 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>
<html>
<body>
<script>
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');
console.log(sandwiches);
console.log(evenMoreSandwiches);
</script>
</body>
</html>
Output:
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