Reputation: 585
Where foo is a defined variable, why is it that the following code:
var array = [].push(foo);
when outputted, equals 1?
From my tests, outputting array will simply output the length of the array.
So the code:
var array = [10,20].push(foo);
would give a value of 3.
As a related question (and to clarify what my code intended to do), why does this not intuitively do what it appears to do, ie:
var array = [];
array.push(foo);
where outputting array gives the expected result of [foo]?
Upvotes: 2
Views: 2426
Reputation: 176
The definition of push()
method including two parts in javascript: Part 1: it adds one or more elements to the end of an array, part 2: it returns the new length of the array.
I think you are missing the part 2 in your understanding of this method.
Upvotes: 0
Reputation: 2261
Because the return value of push is the new length of the array Documentation and examples.
In your second example, you cited outputting the array, which is going to give you the new array in both cases. However, the returned result of your second case is the new array length as well
var array = [];
array.push(foo); //If you do this in the console, you'll see that 1 gets returned.
console.log(array); //While this will print out the actual contents of array, ie. foo
Upvotes: 1
Reputation: 100381
push
is a function and it returns an integer representing the length of the array.
Imagine the definition of this function as
int push(object obj);
When you do this:
var array = [].push(foo);
You are actually running the function and returning the value.
Upvotes: 1
Reputation: 1505
instead you can try
var array, foo = 30;
(array = [10,20]).push(foo);
console.log(array)
Upvotes: 1
Reputation: 10620
Array.prototype.push()
always returns the new number of elements in the array. It does not return this
instance or a new Array instance. push()
is a mutator actually changes the contents of the array.
Upvotes: 1
Reputation: 109
When you use push method it returns length of array. So when you do:
var array = [10,20].push(foo);
you get [10, 20, foo] length of this array is three. But as you say var array it stores returned length from push method in this variable.
Upvotes: 3