How to use Array.push and return the pushed item?

  • A+
Category:Languages

I am calling return someArr[someArr.push(newItem)-1]; and it does pretty what it should.

Wondering is there a syntactic "sugar" for that extremely common operation? I wonder because returned new length is indeed more rarely needed, than actual constructed object (which caller definetely may want to polulate). Or is that made because it actually will return "a copy of an object", and my edits to its fields "will not survive" in actual tree?

Just like a JS <= 1.2 did: return someArr.push(newItem);

Just want to know - Is there are new "replacement" method, that I am unaware of?


Also I had a minor subquestion "does that return an 'independent' copy of an object or a 'reference' to actual object?" but simple fiddle by @PatricRoberts just figured out that it is actually a reference (as it was expected), so I've credited him, for his assistance!

 


You could also do it using a logical and (&&).

return someArr.push(newItem) && newItem; 

Since the array length will be positive after the push, the right-most expression will be evaluated and its value returned.

This syntax is less clear than @adiga's answer using the comma operator though.

However, I personally prefer to return the new item on a new line to make it more readable:

someArr.push(newItem); return newItem; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: