If you need to be able to embed arrays, I would .add() function so that .concat() duplicates Array in the variable, .push() new value in the new array and returns it.
function add(arr) { var newArr = arr.concat(); // duplicate newArr.push("e"); // push new value return newArr; // return new (modified) Array }
You can also use concat() and return the new array that 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 the two methods .slice() , then .push() , you will execute it with one .concat() .
This also gives the advantage of passing another array instead of a string, therefore:
return arr.concat(["e","f"]);
will provide you with:
// ["a", "b", "c", "d", "e", "f"]
instead:
// ["a", "b", "c", "d", ["e", "f"] ]