注: 此为英文资料整理,如需翻译请私信或留评论
Definition
Converting a value from one type to another is often called “type casting,” when done explicitly, and “coercion” when done implicitly (forced by the rules of how a value is used).
Another way these terms are often distinguished is as follows: “type casting” (or “type conversion”) occur in statically typed languages at compile time, while “type coercion” is a runtime conversion for dynamically typed languages.
var a = 42;
var b = a + ""; // implicit coercion
var c = String( a ); // type casting
Coercion to false
From that table, we get the following as the so-called “falsy” values list:
- undefined
- null
- false
- +0, -0, and NaN
- “”
These value will be coerce to false if you force a boolean coercion on it.
Usage
Using Logical Operators with Non-Boolean Values
The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
"foo" && "bar"; // "bar"
"bar" && "foo"; // "foo"
"foo" && ""; // ""
"" && "foo"; // ""
"foo" || "bar"; // "foo"
"bar" || "foo"; // "bar"
"foo" || ""; // "foo"
"" || "foo"; // "foo"
Both && and || result in the value of (exactly) one of their operands:
- A && B returns the value A if A can be coerced into false; otherwise, it returns B.
- A || B returns the value A if A can be coerced into true; otherwise, it returns B.
Reference:
- https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript
- https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md#operators–and-