usercj
usercj

Reputation: 35

How does it work push empty array into an empty array

var ar = []; 
console.log(ar.push([]));   // 1 

I expected the log to be [[]], but it show me 1. What is going on above the code.

Upvotes: 1

Views: 3403

Answers (1)

Nisarg Shah
Nisarg Shah

Reputation: 14561

According to MDN, the Array#push returns:

The new length property of the object upon which the method was called.

So, in your case, as you are pushing an element to an empty array - which makes the length 1 - hence the result.

In case you wish to confirm:

// Empty array.
var arr = [];

// Push an item: result = 1
console.log(arr.push([]));

// Push another item: result = 2
console.log(arr.push([]));

Upvotes: 1

Related Questions