a blog for those who code

Friday, 28 April 2017

Mutating and Non-Mutating JavaScript Array Functions

In this post we will be discussing about Mutating and Non-Mutating JavaScript Array Functions. Mutation in context of JavaScript arrays is basically changing the array itself instead of returning a new array with the new changes whereas Non-Mutation is returning a whole new array which has all the changes.

JavaScript offers a lot of ways to add, remove or replace items in an array and some of them mutate the array (changes the original array) whereas some of them create a new array. We will see all the JavaScript Array Functions which Mutate the array and which does not mutate the array.

Mutator Methods in JavaScript are array.copyWithin(), array.fill(), array.pop(), array.push(), array.reverse(), array.shift(), array.sort(), array.splice() and array.unshift().

Non-Mutating Methods in JavaScript are array.concat(), array.includes(), array.indexOf, array.join(), array.lastIndexOf, array.slice(), array.toString() and array.toLocaleString().

Adding new item to the Array - In JavaScript you can use array.push(), array.unshift(), array.concat() to add new element into an array. Push adds an item to the end of the array whereas unshift adds an item to the beginning of the array and both of them mutates the original array whereas concat returns a whole new array after adding an item.

Removing an item from the Array - In JavaSript you can use array.pop(), array.shift(), array.slice() to remove an element from an array. Pop removes an item at the end of the array, shift removes an item at the beginning of the array and slice extracts a section of an array and returns a new array.

Note : Immutability or Non-Mutation JavaScript array functions are better to some extent because it maintains the predictability and it increases performance by sharing the structure to reduce memory overhead.

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment