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 :)
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 :)
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)
It will check that .Picture2
has been defined, if it has use that value, else assign Window.Picture2
to a new object literal.
As @Christoph states - Picture2
will be assigned a new object literal, if the object is falsy
.
It is read as :
If window.Picture2 is undefined or null assign empty object to window.Picture2