Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var foo = foo || alert(foo);

Can someone explain what this does?

var foo = foo || alert(foo);
like image 323
Atomix Avatar asked Dec 01 '10 19:12

Atomix


People also ask

What is var Foo?

So you need to use var FOO = FOO || {}; which means "FOO will be assigned to FOO (if it exists already) or a new blank object (if FOO does not exist already).

What is the value of Foo?

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. Foo and other words like it are formally known as metasyntactic variables.


3 Answers

If foo is already defined and evaluates to true, it sets foo = foo, i.e. it does nothing.

If foo is defined but evaluates to false, it would popup whatever foo is (false, null, undefined, empty string, 0, NaN), but since alert returns nothing, foo will be set to undefined.

If foo is not yet defined, an exception will be thrown. (Edit: In your example, foo will always be defined because of the var foo declaration.)

like image 104
casablanca Avatar answered Oct 19 '22 14:10

casablanca


If foo evaluates to false (e.g. false, null or zero), the value after the || operator is also evaluated, and shows the value.

The alert method doesn't return a value, so foo will become undefined if it evaluated to false, otherwise it will be assigned it's own value.

like image 41
Guffa Avatar answered Oct 19 '22 12:10

Guffa


var foo;

if (foo)
    foo = foo;
else
    foo = alert(foo); // probably undefined
like image 3
Alon Gubkin Avatar answered Oct 19 '22 14:10

Alon Gubkin