I have recently downloaded a code from web and trying to understand it. I have found one line right above the js file which can be seen as below:
var Liip = Liip || {};
Can someone explain to me what is this line doing?
I have recently downloaded a code from web and trying to understand it. I have found one line right above the js file which can be seen as below:
var Liip = Liip || {};
Can someone explain to me what is this line doing?
It means that Liip
will either hold Liip
and if it is not defined, then it will be an empty object {}
This is a common idiom used to assign default values to things that haven't been specified.
In this instances, it makes Liip
default to an empty object.
The main pitfall is that it is based on the notion of "truthiness", and would replace things like the number zero with the default.
If Liip
is undefined
it will assign {}
.
It can be expressed also as:
Liip = Liip? Liip: {};
OR
if (Liip){
Liip = Liip;
}
else {
Liip = {};
}
OR
if (typeof(Liip) === 'undefined'){
Liip = {};
}
else {
Liip = Liip;
}
For reference: It's equivalent to C#:
int? nullableInt = getNumber();
int Liip = nullableInt?? 0;
this is a trick of using lazy evaluation
if you type something like:
if (true || false)
Then the interpreter doesn't look at false
at all as this doesn't have any impact to the result. That's because ||
(or) will return true
IF ANY of the components is true and when we know that the first part evaluates to true
, then we can be sure that the whole sentence evaluates to true
(in javacript it's even more simplified by simply returning this part)
so
true || anything || something
always return true
and if the first part evaluates to false
, then the interpreter looks at the next part consequently and returns anything
or something
if anything
is false as well.
this way
0 || 0 || 2
returns 2
0 || 3 || 3
returns 3
and:
undefined || {}
returns {}
true || {}
returns true
You can also use &&
to make interpreter look at the next part if the first part is NOT equal to false
true && 2
returns 2
false && 2
returns false
that's because &&
(AND) returns true
if all of the components evaluates to true
. So there's no need to look at 2
if the first part is false
.