Array push JavaScript vs Ruby | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Array push JavaScript vs Ruby

My first programming language is Ruby. Today I ran into a strange issue in my code in JavaScript. //Node.js var array = [ ]; array = array.push(0); console.log(array); //Strangely the output is 1. Why?? #Ruby array = [ ] array = array.push(0) print(array) As expected the output is [0]. Could anyone please explain the difference in output in these (very similar) codes in Ruby and JavaScript?

24th Mar 2021, 10:24 PM
Mírian Fonkam
Mírian Fonkam - avatar
3 Answers
+ 3
This will return the expected output. var array = []; array.push(0); console.log(array); The push() returns the length of the array which is the reason behind it printing 1.
24th Mar 2021, 10:41 PM
Avinesh
Avinesh - avatar
+ 2
Like append in python, the push() function in ruby used to push one or more elements into the array just like adding a new element in an array.
24th Mar 2021, 10:28 PM
Dino Wun (Use the search bar plz!)
Dino Wun (Use the search bar plz!) - avatar
0
Yes, push on a JavaScript array returns the length of the array as was said above. That's the new length (after the push). This is different from Ruby where the array you're pushing to is returned. It's important to remember not to save the value of a push like this in JavaScript.
24th Mar 2021, 11:14 PM
CamelBeatsSnake
CamelBeatsSnake - avatar