Reputation: 15927
Currently I check if sed object already exists as to not wipe it if it does, then create the object.
if (typeof result === 'undefined') {
results = {};
}
It's just that I come from using PHP where you don't really have to declare things as much as you do in JS.
Though I tend to use JS objects as I use arrays in PHP, as a way to temporarily store information which I need to access further down in a script.
Upvotes: 1
Views: 63
Reputation: 48546
Just write your code so you never have to guess. Avoid globals, don't create variables conditionally, set defaults early. You should only need your pattern in special cases, like writing a library for third parties, using a module system, etc.
Upvotes: 2
Reputation: 129011
This wouldn't work if certain values (e.g., 0
, null
, or false
) should not be overwritten, but:
results = results || {};
This works because ||
returns the first value if it is truthy or the second otherwise. undefined
, along with some other values partially listed above, are falsy, but objects are truthy.
Upvotes: 3