Skip to content

Instantly share code, notes, and snippets.

@hollygood
Created February 3, 2019 00:46
Show Gist options
  • Save hollygood/bfe2019f3d1277a4118873e96ac05d5a to your computer and use it in GitHub Desktop.
Save hollygood/bfe2019f3d1277a4118873e96ac05d5a to your computer and use it in GitHub Desktop.
Javascript Mutating vs Non-Mutating functions
// ADD: Mutating
let mutatingAdd = ['a', 'b', 'c', 'd', 'e'];
// array.push() adds an item to the end of the array
// array.unshift() adds an item to the beginning of the array.
mutatingAdd.push('f'); // ['a', 'b', 'c', 'd', 'e', 'f']
mutatingAdd.unshift('z'); // ['z', 'a', 'b', 'c', 'd', 'e'
// ADD: NON MUTATING
// concat
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = arr1.concat('f'); // ['a', 'b', 'c', 'd', 'e'. 'f']
console.log(arr1); // ['a', 'b', 'c', 'd', 'e']
// spread operator
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = [...arr1, 'f']; // ['a', 'b', 'c', 'd', 'e', 'f']
const arr3 = ['z', ...arr1]; // ['z', 'a', 'b', 'c', 'd', 'e']
// REMOVE: MUTATING
let mutatingRemove = ['a', 'b', 'c', 'd', 'e'];
mutatingRemove.pop(); // ['a', 'b', 'c', 'd']
mutatingRemove.shift(); // ['b', 'c', 'd']
mutatingRemove.splice(0, 2); // ['c', 'd', 'e']
// REMOVE: NON MUTATING
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = arr1.filter(a => a !== 'e'); // ['a', 'b', 'c', 'd']
// OR
const arr2 = arr1.filter(a => {
return a !== 'e';
}); // ['a', 'b', 'c', 'd']
const arr2 = arr1.slice(1, 5) // ['b', 'c', 'd', 'e']
const arr3 = arr1.slice(2) // ['c', 'd', 'e']
// REPLACE: MUTATING
let mutatingReplace = ['a', 'b', 'c', 'd', 'e'];
mutatingReplace.splice(2, 1, 30); // ['a', 'b', 30, 'd', 'e']
// OR
mutatingReplace.splice(2, 1, 30, 31); // ['a', 'b', 30, 31, 'd', 'e']
// REPLACE NON MUTATING
const arr1 = ['a', 'b', 'c', 'd', 'e']
const arr2 = arr1.map(item => {
if(item === 'c') {
item = 'CAT';
}
return item;
}); // ['a', 'b', 'CAT', 'd', 'e']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment