Search code examples
javascriptarraysecmascript-6chaining

How to clone an array and push new value in a chain?


If I clone an array and push a value like so:

var arr1 = ["foo", "bar"];
var arr2 = [...arr1];
arr2.push("moo");

console.log(arr2); //["foo", "bar", "moo"]

it behaves as I would expect. However, if I chain the push method like so:

var arr1 = ["foo", "bar"];
var arr2 = [...arr1].push("moo");

console.log(arr2); //3 WTF?

I didn't expect that. Why does chaining .push() like the second example return the number 3 and not an array of values?


Solution

  • array.push returns the new length of the array which you're storing in arr2 variable.

    You need the following:

    var arr1 = ["foo", "bar"];
    var arr2 = arr1.concat("moo");
    console.log(arr2);