+ 1

Why push function in javascript showing the length of array?

I tried running this code. var arrayone = ["Rose","Milk","ghee"] arrayone = arrayone.push("kill") console.log(arrayone) console output is 4 Can anyone explain this.

18th Sep 2020, 9:40 AM
Lucifer
Lucifer - avatar
8 Réponses
+ 3
You don't have to make it arrayone= arrayone.push("kill") because push returns the length of the array so the arrayone variable will be now the length, however if you just call it on the array like arrayone.push then it will add the item and the output will be the new array with the new item
18th Sep 2020, 9:49 AM
Ruba Kh
Ruba Kh - avatar
+ 10
Because it returns length of the array
18th Sep 2020, 9:45 AM
TOLUENE
TOLUENE - avatar
+ 1
Using push you added "kill" to the end of "arrayone" array. Now the length of that array is 4 not 3!!! In the end, You changed variable arrayone from array to integer Then you called that var in console
18th Sep 2020, 9:49 AM
Shadoff
Shadoff - avatar
+ 1
Ruba Kh If, push function returns the value of length in general, then while running console.log(arrayone.push) it should return number?
18th Sep 2020, 9:56 AM
Lucifer
Lucifer - avatar
0
Why is this returning the length of array?
18th Sep 2020, 9:46 AM
Lucifer
Lucifer - avatar
0
This is why I recommend reading documentations.
18th Sep 2020, 9:59 AM
Raj Chhatrala
Raj Chhatrala - avatar
0
Yup exactly Lucifer It will add an item also try this to understand var arrayone = ["Rose","Milk","ghee"] console.log(arrayone.push("kill")) console.log(arrayone)
18th Sep 2020, 9:59 AM
Ruba Kh
Ruba Kh - avatar
0
@RDC I tried reading the MDN documentation but couldn't find the answer, if you have read it and found the answer, it would be better to if you just can answer.
18th Sep 2020, 10:01 AM
Lucifer
Lucifer - avatar