JavaScript Boolean Evaluation
So what is the output here?
Explanation: The value "to be"
is evaluated to “true.” The OR logical operator returns the first operand if that operand is evaluated to be true.
Boolean-ish: truthy or falsy values!
- If a value can be converted to true, the value is so-called truthy.
- If a value can be converted to false, the value is so-called falsy.
0
, NaN
, null
, undefined
, empty string (""
or ''
or ````) are all falsy.
- All other values are truthy.
Logical operators (as well as if/loop conditions) embrace Boolean-ish!
The Boolean-ish is embraced by the JavaScript community too. For instance, it is common to see code like this
Which can easily be converted to
Another everyday use is to set a default value to a function argument.
Which can easily be avoided by using default function parameters! (We will cover functions in a future chapter.)
My advice is to avoid tricky or hacky expressions! Code what you mean! Especially when it is not much more work to do so.
There are cases where it might be more work; for example, the following expression
does the job of the code below:
Here is another one:
which does the job of the following code: