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 :-(
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({});
The best I can think of is:
var obj;
(obj = (obj || [])).push({});
obj should always be undefined in this case, which makes the (obj || []) just []var obj; won't set obj to undefined if it was defined before.var obj twice in the same scope, which just seems like a waste of the var to me...Just a tiny tweak to your idea to make it work
var obj = (obj || []).concat([{}]);
concat actually returns a completely new array... Meaning if obj was already defined (which i'm still curious how that might happen), it will not have the {} added to it in any parent scope...obj should either stay as it is, or become an empty array, then push something onto it... The problem being that push wouldn't happen on the original obj so if that obj was a reference to a different array, or a function parameter, etc... your code would not do the same thing...obj.push() executes no matter what the original state of obj iswith(obj = obj || []) push({});
(obj || [{}]) is functional.with statement as Douglas Crockford told me (yuiblog.com/blog/2006/04/11/with-statement-considered-harmful) that bad unforseen things can happen on its usage{} to the array if it didn't already exist, and leave it as is otherwise. I realized this shortly after I posted. @Spudley - please explain why its usage is harmful in this case. @sod - and what bad unforeseen things could possibly happen with this simple line of code? There is no ambiguity at all.with is a powerful tool whether crockford likes it or not, it's just a matter of understanding the tool as is everything else. A good coder knows when to break rules.
var obj.. afterif(!obj), doesn't make a lot of sense, isobjalso defined in a higher scope or something?varlike that... I'm assumingobjis probably a function parameter, and the keywordvarin there is just useless / unwanted... If not, there is no wayobjcould ever be defined before this call... Tryobj={}; (function() { if (!obj) var obj = []; console.log(obj); })();-- You'll get[]