Question

I want to clone a new array from an existing one and push in an element. Unfortunately, the existing array is an empty one, so it's like:

[].slice().push(65)

the output of above expression is 1.

Why is it 1?

Was it helpful?

Solution

Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.

If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:

var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]

OTHER TIPS

Changing my comment to an answer:

MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.

You need to do it in two steps, not one with that pattern.

var temp = [].slice();
temp.push(65);
console.log(temp);

If you want to do it in one line, look into concat()

var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top