DEV Community

James L
James L

Posted on • Edited on

πŸŽ„JS Advent #2 - Mutable and Immutable methods πŸŽ„

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]
Enter fullscreen mode Exit fullscreen mode

push:

// reset the array
let arr = [1,2,3,4];
arr.push(5);
console.log(arr); // [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

reverse:

 // reset the array
let arr = [1,2,3,4];
arr.reverse();
console.log(arr); // [4,3,2,1]
Enter fullscreen mode Exit fullscreen mode

unshift:

// reset the array
let arr = [1,2,3,4]; 
arr.unshift(1);
console.log(arr); // [1,1,2,3,4]
Enter fullscreen mode Exit fullscreen mode
  • 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]
Enter fullscreen mode Exit fullscreen mode

map:

let arr = arr.map(el => el * 2);
console.log(arr); // [1,2,3,4]
console.log(newArray); // [2,4,6,8]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

slice:

let newArray = arr.slice(2)
console.log(arr); // [1,2,3,4]
console.log(newArray); // [3,4,]
Enter fullscreen mode Exit fullscreen mode
  • 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.

< JS Advent #1

Top comments (2)

Collapse
 
mytechpal profile image
Darrick Fauvel

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.

Collapse
 
jtlavs profile image
James L

Thank you, I have corrected this in the article.