Skip to content Skip to sidebar Skip to footer

Javascript Syntax: Var Array = [].push(foo);

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 leng

Solution 1:

When you use push method it returns length of array. So when you do:

vararray = [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.

Solution 2:

instead you can try

vararray, foo = 30;
  (array = [10,20]).push(foo);
  console.log(array)

Solution 3:

push is a function and it returns an integer representing the length of the array.

Imagine the definition of this function as

intpush(object obj);

When you do this:

vararray = [].push(foo);

You are actually running the function and returning the value.

Solution 4:

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

vararray = [];
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

Solution 5:

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.

Post a Comment for "Javascript Syntax: Var Array = [].push(foo);"