Non Mutating List Operations
Array operations in JavaScript can be annoying because they modify the base list. Which can lead to potentially confusing side effects like this:
var list = [2,1,3,4]; var doSomething = function(newList) { return newList.reverse(); }; console.log(doSomething(list));// [4, 3, 1, 2] console.log(list);// [4, 3, 1, 2]
Fortunately, this can be easily avoided by a little trick. By doing an [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) which returns a shallow copy of the list and not a reference of it. It just returns the whole list when passed no arguments:
list = [2,1,3,4]; doSomething = function(newList) { return newList.slice().reverse(); } console.log(doSomething(list)); // [4, 3, 1, 2] console.log(list);// [2, 1, 3, 4]
It has the same effect for sort too lists too:
list = [2,1,3,4]; var sortedList = list.slice().sort(); console.log(sortedList); // [1, 2, 3, 4] console.log(list);// [2, 1, 3, 4]
Just keep in mind slice does not clone; If a list property is an object, then modifying a property on one list will affect the other.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/nonMutatedLists.js













