Using Javascript logical OR operator as an default operator

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

The Javascript logical OR operator works like this …

If the first operand is truthy (see what is truthy and falsy), it will return the first operand.  Otherwise it will return the second operand.

So this code will output green…

will output green

will output green

because there is value passed into color making the first operand truthy.

However, this code will output blue (the default value if no color is passed) …

will output blue

will output blue

because “color” is undefined here.  And undefined is falsy.  So the second operand is returned.