For the month of December I have challenged myself to write 24 articles about JS up until Xmas.
The second installment in this series is around Mutable and Immutable array methods.
What is a mutable method?
- A mutable method is a method which changes the state of the array it is called on.
eg.
splice
,pop
,push
,unshift
,shift
,reverse
What is an immutable method?
- An immutable method is a method which does not change the state of the array it is called on and sometimes returns a new array instead.
eg.
concat
,map
,slice
,filter
Examples of array mutation methods
pop:
let arr = [1,2,3,4];
console.log(arr); // [1,2,3,4]
arr.pop();
console.log(arr); // [1,2,3]
push:
// reset the array
let arr = [1,2,3,4];
arr.push(5);
console.log(arr); // [1,2,3,4,5]
reverse:
// reset the array
let arr = [1,2,3,4];
arr.reverse();
console.log(arr); // [4,3,2,1]
unshift:
// reset the array
let arr = [1,2,3,4];
arr.unshift(1);
console.log(arr); // [1,1,2,3,4]
- The value of the original array has changed in every instance.
Examples of array immutable methods
filter:
let arr = [1,2,3,4];
let newArray = arr.filter(el => el > 2);
console.log(arr); // [1,2,3,4]
console.log(newArray); // [3,4]
map:
let arr = arr.map(el => el * 2);
console.log(arr); // [1,2,3,4]
console.log(newArray); // [2,4,6,8]
concat:
let newArray = arr.concat([5,6,7]);
console.log(arr); // [1,2,3,4]
console.log(newArray); // [1,2,3,4,5,6,7]
slice:
let newArray = arr.slice(2)
console.log(arr); // [1,2,3,4]
console.log(newArray); // [3,4,]
- The original array stays the same when the immutable methods are called on it.
Pure functions
- A pure function is a function which as well as returning the same result every time it is executed with the same inputs also does not have any other side affects.
- Using immutable array methods in functions contributes to this as they do not produce the side effect of changing the array.
Top comments (2)
In the pop method example, the last element in the array will be popped off the array. So, the commented result should read "// [1, 2, 3]".
Thanks for writing these articles. I look forward to reading more.
Thank you, I have corrected this in the article.