Logical operators in JavaScript
Most of us who are more familiar with static typed languages like
java, c#, c++, c etc, know that logical "and" and "or" can be applied
on boolean values. Well Javascript (or may be even other dynamic
languages) let you apply these operators on any type.
The way it works :
1. The || ("OR") operator - The expression on the left hand side of
the operator is evaluated. If that expression is true, the value on
the right is returned as it is which in turn is converted to boolean.
So basically something like ("" || "hello") would return "hello" which
when converted to boolean returns true.
2. The && operator works similarly, but the other way around. When the
value to its left is something that would give false when converted to
a boolean, it returns that value, and otherwise it returns the value
on its right. (picked straight from this book)
The way javascript handles boolean is also pretty odd. Only 0, "", null
and undefined when converted to boolean map to false, even a "false"
string in javascript when converted to boolean returns true, Funny eh? Small pleasures of life!
java, c#, c++, c etc, know that logical "and" and "or" can be applied
on boolean values. Well Javascript (or may be even other dynamic
languages) let you apply these operators on any type.
The way it works :
1. The || ("OR") operator - The expression on the left hand side of
the operator is evaluated. If that expression is true, the value on
the right is returned as it is which in turn is converted to boolean.
So basically something like ("" || "hello") would return "hello" which
when converted to boolean returns true.
2. The && operator works similarly, but the other way around. When the
value to its left is something that would give false when converted to
a boolean, it returns that value, and otherwise it returns the value
on its right. (picked straight from this book)
The way javascript handles boolean is also pretty odd. Only 0, "", null
and undefined when converted to boolean map to false, even a "false"
string in javascript when converted to boolean returns true, Funny eh? Small pleasures of life!
nice :)
ReplyDelete