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'])
foo = foo || [];pushfunction? otherwise you could just havewindow.foo = window.foo || ['bar']baronto an existingfootoo.