What does this Javascript code mean?

Possible duplicate:
What does "options = options || {}" mean in Javascript?

Looking at a YouTube source ...

var yt = yt || {}; 

Does it mean. set yt to yt if yt exists, otherwise create a new object?

If so, I did not think that you could make a condition when declaring a variable.

+3
source share
4 answers

Assign the yt value back to yt if it does not have the value 0 , NaN , false , null , "" or undefined (that is, it is false) in this case, assign {} yt .

This works because each of the values โ€‹โ€‹in the above list evaluates to false in a boolean expression.

+4
source

This means that: if the content is not evaluated as false, assign it to yourself (which is a neutral operation), otherwise create a new object and assign it yt . It is commonly used to instantiate objects for use as namespaces, first checking to see if a namespace exists.

+3
source

Evaluate yt if it evaluates to false, then create it as an object.

The first time I saw something like this:

 function handleEvent(e){ e=e||window.event; } 

pretty nifty ~ does anyone know of other languages โ€‹โ€‹that support this syntax? (Not PHP = (

+1
source

Yes, the entire right side of the expression is evaluated first before the appointment. Therefore, if yt==false value of the expression in RHS will be {} and passed to var yt

0
source

All Articles