An Easy Way to See JavaScript Mutables
Understanding mutables can help your overall knowledge of JavaScript. Get a simple understanding of JavaScript mutables using the splice and slice methods.
Table of Contents 📖
Mutables
A mutable is a type of variable that can be changed without creating a new value. In JavaScript, reference types are mutable (objects, arrays, and functions).
splice
An easy way to view mutables in JavaScript is slice vs splice. Both of these methods are used to modify arrays. However, the splice method is mutating. In other words, it mutates the original array.
INFO: An immutable is the opposite of a mutable, it is a value that cannot be changed once it is created.
const mutableRef = [1, 2, 3];
const mutableRef2 = mutableRef;
console.log('mutableRef', mutableRef);
console.log('mutableRef2', mutableRef2);
// 1 (start index): Specifies the position in the array where the operation begins (0-based index).
// 1 (start index): Specifies the position in the array where the operation begins (0-based index).
mutableRef.splice(1, 1);
console.log('mutableRef', mutableRef); // [1, 3]
console.log('mutableRef2', mutableRef2); // [1, 3]
Here, we can see that both mutableRef and mutableRef2 are pointing to the same array. Because of this, when the splice method is called on mutableRef, the changes are reflected in both mutableRef and mutableRef2.
slice
On the other hand, slice returns a new array and does not mutate the original array.
const mutableRef = [1, 2, 3];
const mutableRef2 = mutableRef;
console.log('mutableRef', mutableRef);
console.log('mutableRef2', mutableRef2);
// extracts the first two elements
// 0 (start index): The position where the extraction begins (inclusive).
// 2 (end index): The position where the extraction ends (exclusive).
const newArray = mutableRef.slice(0, 2);
console.warn('mutableRef', mutableRef); // [1, 2, 3]
console.warn('mutableRef2', mutableRef2); // [1, 2, 3]
console.error('newArray', newArray); // [1, 2]
If we look at the output, we can see that neither mutableRef nor mutableRef2 are mutated. This is because, unlike splice, slice is not a mutating method.