-1
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var a = ['a','b'];
var b = ['c','d'];
var c = a.concat(b).push('e');
document.getElementById("demo").innerHTML = c;
</script>

</body>
</html>

This will lead to the number '5', instead of ['a','b','c','d','e']

wmock
  • 5,382
  • 4
  • 40
  • 62
Burton
  • 53
  • 6
  • 9
    First sentence of the documentation: "[The push() method adds one or more elements to the end of an array and returns the new length of the array.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – Raymond Chen Jan 11 '15 at 04:12
  • Not sure what you mean by why...since that's what the documentation specifies – wmock Jan 11 '15 at 04:14
  • Read the documentation of the method before asking questions about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push Hint: Google search "javascript Array push MDN" – unobf Jan 11 '15 at 04:15
  • If you want the last value back, use the resulting length as part of the look up. Of course, this could be a little confusing for others when reading your code: `var val = arr[arr.push("val")-1]`. – Sampson Jan 11 '15 at 04:20

1 Answers1

1

By definition, the push() method returns the new length property of the object upon which the method is called.

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

Here,

a.concat(b) //returns an `array`. But wait, the statement still has a method chained,
            //and to be evaluated.
(returned array).push('e'); // the chained push() is invoked on the returned array.

which in turn returns the length of the newly formed array. So the final return value of the statement is the length of the array, which is stored in the c variable.

To capture the returned array by the concat() operation, you can modify your code to break down the chained methods into multiple statements, as below:

var c = a.concat(b);
c.push('e');
console.log(c) // prints the array content.
BatScream
  • 19,260
  • 4
  • 52
  • 68
  • @Ja͢ck - Might be the OP was confused with the chained application of the the `concat()` and `push()` methods. – BatScream Jan 11 '15 at 04:44
  • 1
    `the statement has not ended unless a \`;\` is encountered` - [That's not always true with JavaScript](http://stackoverflow.com/q/2846283/1903116) ;) – thefourtheye Jan 11 '15 at 05:42