Reputation: 12716
I was trying to understand the point of var myObj = myObj || {};
and found this and this article explaining it. But I still don't see the situation in which I'd need it. Those articles seem to address the actual logic of it as its equivalence to a ? a : b
- I get that.
For example, I'm creating a HUD for my game,
game.HUD = game.HUD || {};
game.HUD.Container = me.Container.extend({
//...
Why can't I just create the object without using game.HUD = game.HUD || {};
?
Upvotes: 0
Views: 81
Reputation: 36458
It's mainly a safety thing. You want:
game.HUD
regardless of whether it was previously initializedgame.HUD
was already initialized to remain.If game.HUD
already existed, then
game.HUD = {};
would wipe out any data assigned to it.
game.HUD = game.HUD || {};
initializes it if necessary, and otherwise leaves it alone, so that either way
game.HUD.Container = ...
works.
Upvotes: 1
Reputation: 245479
If you know you need to initialize game.HUD
for certain, then you don't need to use your snippet.
If there's a possibility that game.HUD
held a previous value that you don't want to overwrite, then that's when you would use your sample code.
Upvotes: 3