sod
sod

Reputation: 3928

Elegant way to init and extend a javascript array

Is there a sweet way to init an array if not already initilized? Currently the code looks something like:

if (!obj) var obj = [];
obj.push({});

cool would be something like var obj = (obj || []).push({}), but that does not work :-(

Upvotes: 15

Views: 12111

Answers (5)

mckeed
mckeed

Reputation: 9818

If the variable has already been declared it can be done with nullish coalescing assignment:

(obj ??= []).push({});

Upvotes: 0

MooGoo
MooGoo

Reputation: 48240

with(obj = obj || []) push({});

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105878

Just a tiny tweak to your idea to make it work

var obj = (obj || []).concat([{}]);

Upvotes: 2

RoToRa
RoToRa

Reputation: 38400

The best I can think of is:

var obj; 
(obj = (obj || [])).push({});

Upvotes: 2

Kobi
Kobi

Reputation: 138007

var obj = (obj || []).push({}) doesn't work because push returns the new length of the array. For a new object, it will create obj with value of 1. For an existing object it might raise an error - if obj is a number, it does not have a push function.

You should do OK with:

var obj = obj || [];
obj.push({});

Upvotes: 18

Related Questions