Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I push inside an array and use it in a function argument in javascript?

Why are b and c are not identical in the below code? What is the order of statement execution in line number 2?

var a = [1,2];
var b = new Array(a.push(1)); //[undefined, undefined, undefined]
var c = new Array(a);         // [[1, 2, 1]]

1 Answers

The .push() function returns the new length of the array, not the array itself. Thus, b is initialized to a 3-element empty array because .push() returns 3 (after adding the 1 to the end of the array a).

like image 175
Pointy Avatar answered Jan 29 '26 19:01

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!