Javascript logical AND operator does not necessarily return boolean true false

Posted in Tutorials

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

If you came from other programming language, you might expect the Javascript boolean operator to return a boolean true or false.  But this is not necessarily the case in Javascript.  It will return a truthy or falsy value, but not necessarily a boolean.  Everything in Javascript is either truthy or falsy.

Take the example, …

Javascript logical AND

Javascript logical AND

If alpha and beta are booleans, then sure Javascript will return a boolean true or false as expected.    If both alpha and beta is true, then the condition is true.   Otherwise, condition is false.

But if they were …

var alpha = “Hello”;
var beta = “World”;

The result of alpha && beta is “World”, which is truthy and the first if-branch will run.

result of Javascript AND

result of Javascript AND

This is because the rule for Javascript AND is …

If the first operand is truthy, return the second operand.  Otherwise, return the first operand.

Since alpha of “Hello” is truthy, the operator returned beta, which is “World”.

If the second operand is a function invocation, the function will execute only if first operand is truthy. Here…

function as second operand

function as second operand

If there is a name value for “name”, the alert will occur.  If name is an empty string (which is falsy), the greet function will not run.