Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Javascript code mean? [duplicate]

Tags:

javascript

Possible Duplicate:
What does “options = options || {}” mean in Javascript?

Looking at the YouTube source...

var yt = yt || {};

Does that mean.. set yt to yt if yt exists, else create a new object?

If that's the case, I didn't think you can put a condition when declaring a variable.

like image 270
Marko Avatar asked Mar 04 '26 04:03

Marko


2 Answers

Assign the value of yt back to yt unless it is any of 0, NaN, false, null, "", or undefined (i.e. it's falsy), in which case assign {} to yt.

This works because each of the values in the list above evaluate to false in a boolean expression.

like image 59
Wayne Avatar answered Mar 06 '26 01:03

Wayne


It means exactly that: If the content does not evaluate to false, assign it to itself (which is a neutral operation), otherwise create a new object and assign it to yt. It's typically used to instantiate objects to use as namespaces, first checking if the namespace already exists.

like image 31
Stefano Borini Avatar answered Mar 06 '26 03:03

Stefano Borini