user494461
user494461

Reputation:

Why cant I push inside an array and use it in a function argument in javascript?

Why are b and c are not identical in the below code? What is the order of statement execution in line number 2?

var a = [1,2];
var b = new Array(a.push(1)); //[undefined, undefined, undefined]
var c = new Array(a);         // [[1, 2, 1]]

Upvotes: 3

Views: 49

Answers (2)

David Lemon
David Lemon

Reputation: 1560

You can also clone the array using the slice function as an alternative to constructors. And use this way if you want a to remain unchanged.

var a = [1,2];
var b = a.slice(); 
b.push(1);            // [[1, 2, 1]]
var c = b.slice();    // [[1, 2, 1]]

Upvotes: 0

Pointy
Pointy

Reputation: 413720

The .push() function returns the new length of the array, not the array itself. Thus, b is initialized to a 3-element empty array because .push() returns 3 (after adding the 1 to the end of the array a).

Upvotes: 5

Related Questions