Javascript: OR and AND
Thursday, 02 Apr 2009Javascript has an odd and interesting way of processing the || and && operators. Contrary to what might be expected, their return value is not a boolean(!). Instead, both will always return one of the two parameters passed.
OR (||)
a = b || c;Javascript will return b if b is truthy, and c if b is falsy. Instead of directly returning true or false, it will simply pass one of the parameters that has a truthy or falsy value! Note how this perfectly executes the logic of the OR operator. This allows you to use it in an extended context. For example, it allows you to easily define a default value for a parameter:
opacity = this.options.opacity || 0.5;If this.options.opacity was undefined (falsy), the || operator will simply return the second argument (0.5).
AND (&&)
a = b && c;Javascript will return b if b is falsy, and c ifb is truthy. Again this makes sense, since it perfectly executes the logic of the AND operator.
Falsy / Truthy
For completeness, I will list the Javascript falsy values here - quite a list compared to most other languages!- 0 (Number)
- NaN (Number)
- '' (empty String)
- false (Boolean)
- null (Object)
- undefined (undefined)
Ternary Operator (exp ? value1 : value2)
As a consequence the ternary operator has a pattern that can allways be rewritten into a shorter || form:depends = a ? a : b;always equals the simpler
depends = a || b;which is something, most people will overlook. Personally, I think the first example is much clearer to people unfamiliar with Javascript's odd || operator. However, once you are, the second example is much easier to read (the ternary operator usually is not).
Posted in: javascript



Comments (2)
First lets check existence before we try to access an object.
var A = foo.bar && foo.bar.baz
If A would be directly set to foo.bar.baz this would result in an error if foo.bar does not exist. On the other hand with our short circuit testing A will return undefined for no foo.bar.
Now we add an || or symbol to revert to a default value if this.options has no value or if this.options.opacity has no value
opacity = this.options && this.options.opacity || 0.5;
And so forth... happy combining
More on the subject:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
http://en.wikipedia.org/wiki/Lazy_evaluation