Javascript Coercion and Operator Between Non-boolean Values

注: 此为英文资料整理,如需翻译请私信或留评论

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:

  1. https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript
  2. https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md#operators–and-
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值