Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array and push into it in one line

Tags:

javascript

The following is just a theoretical JavaScript question. I am curious if the following can be converting into a single statement:

if(!window.foo){   window.foo = []; } window.foo.push('bar'); 

everyone has probably written this code before, but can it be done in one line?
At first I thought something like this would work:

(window.foo || window.foo = []).push('bar'); 

but that doesn't work because of an invalid assignment. Next I tried chaining something on the push, but that doesn't work because push does not return the array.

Any thoughts on if this can be done in plain JavaScript?
(the result by the way should be that window.foo = ['bar'])

like image 779
mkoryak Avatar asked Jan 30 '13 21:01

mkoryak


People also ask

How do you push something into an array?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

How do you push multiple items into an array?

Use the Array. push() method to push multiple values to an array, e.g. arr. push('b', 'c', 'd'); . The push() method adds one or more values to the end of an array.

Can you push into an array?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.


2 Answers

You've got your assignment backwards*. It should be:

(window.foo = window.foo || []).push('bar'); 

The || operator in JavaScript does not return a boolean value. If the left hand side is truthy, it returns the left hand side, otherwise it returns the right hand side.

a = a || []; 

is equivalent to

a = a ? a : []; 

So an alternative way of writing the above is:

(window.foo = window.foo ? window.foo : []).push('bar'); 

* see comments for details

like image 81
zzzzBov Avatar answered Sep 17 '22 19:09

zzzzBov


Your code works just fine if you add parentheses so that it does what you intended:

(window.foo || (window.foo = [])).push('bar'); 

Without the parentheses, it thinks that it should evaluate window.foo || window.foo first, and then assign the array to the result of that, which is not possible.

like image 30
Guffa Avatar answered Sep 21 '22 19:09

Guffa