When and why use JS null coalescing operator

80 Views Asked by At

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 || {};?

2

There are 2 best solutions below

0
On

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.

0
On

It's mainly a safety thing. You want:

  1. ... the following code to be able to use game.HUD regardless of whether it was previously initialized
  2. ... any fields that were assigned if game.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.