Javascript syntax: var array = [] .push (foo);

Where foo is a specific variable, why is the following code:

var array = [].push(foo);

when output is 1 ?
From my tests, array output will simply output the length of the array.
So the code:

var array = [10,20].push(foo);

will give a value of 3 .

As a related question (and to clarify what my code should have done), why doesn’t it intuitively do what it does, i.e.:

var array = [];
array.push(foo);

where is the output of the array giving the expected result [foo] ?

0
source share
5 answers

push, . , :

var array = [10,20].push(foo);

[10, 20, foo] - . , , var push .

+2

push - .

, . ,

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
0

Array.prototype.push() . this . push() - , .

0

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

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

Imagine defining this function as

int push(object obj);

When you do this:

var array = [].push(foo);

In fact, you run the function and return a value.

0
source

Source: https://habr.com/ru/post/1676305/


All Articles