0

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?

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • Initializing local variable Liip as global (or passed onto function) variable Liip, or, if such global/passed variable doesnt exist, an empty object. Its essentially a default setting. – cernunnos Nov 12 '13 at 12:02
  • 1
    duplicate http://stackoverflow.com/questions/11553314/what-does-javascript-somevalue-mean http://stackoverflow.com/questions/2851404/what-does-options-options-mean-in-javascript – Fabien Sa Nov 12 '13 at 12:05

4 Answers4

3

It means that Liip will either hold Liip and if it is not defined, then it will be an empty object {}

Shlomo
  • 3,880
  • 8
  • 50
  • 82
1

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Would the downvoter care to explain what they think is wrong with the answer? Thanks. – NPE Nov 12 '13 at 15:46
1

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;
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
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.

Adassko
  • 5,201
  • 20
  • 37