Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript statement with || {}; [duplicate]

Tags:

javascript

Im studying javascript and today I found this code :

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

I dont understand the || {} ; Can someone explain this for me? Tks so much :)

like image 650
Duc Anh Avatar asked Apr 22 '13 09:04

Duc Anh


1 Answers

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.

like image 120
Christoph Avatar answered Oct 05 '22 23:10

Christoph