If you need to be able to nest arrays, then I'd change the .add()
function to have the .concat()
duplicate the Array into a variable, .push()
the new value into the new Array, and return it.
function add(arr) {
var newArr = arr.concat(); // duplicate
newArr.push("e"); // push new value
return newArr; // return new (modified) Array
}
You could use concat()
as well, and return the new array it creates.
var myArray = ["a", "b", "c", "d"];
function add(arr) {
return arr.concat("e");
}
var newArray = add(myArray);
console.log( newArray ); // ["a", "b", "c", "d", "e"]
console.log( myArray ); // ["a", "b", "c", "d"]
So instead of two methods .slice()
then .push()
, you accomplish it with one .concat()
.
This also gives you the benefit of passing another Array instead of a string, so:
return arr.concat(["e","f"]);
would give you:
// ["a", "b", "c", "d", "e", "f"]
instead of:
// ["a", "b", "c", "d", ["e", "f"] ]