Javascript statement with || {};

This is a dangerous way to assign a default value to a global variable Picture2.

window.Picture2 = window.Picture2 || {};

This will initialize window.Picture2 as a new Object {} if it is not defined. However since this is a check for truthyness, Picture2 also will be assigned an empty object if it has any of these falsy values:

// these are all falsy
0, NaN, null, '', undefined, false

which might not be the desired behaviour for all these cases, especially for the 0, NaN, false or '' Value.

EDIT
The ?? "NULLISH COALESCING" operator is now part of the ECMAScript standard and has pretty decent browser support already.

So the syntax for your use case would be:

window.Picture2 ?? {};

This will evaluate to false if Picture2 equals undefined or null, but not for the rest of the falsy values.

If you want to assign a default value for a function parameter, you can now also write the following:

function myfunc(Picture2 = {}){
   /* function body */
}

Both, the default parameter syntax and the nullish coalescing operator are the only correct ways to assign default values without side effects.


It assigns a default empty object to window.Picture2 if window.Picture2 is undefined(falsy)

Tags:

Javascript