♦️

JavaScriptで{} + [] = 0になる理由

2022/06/03に公開

概要

Why

理由

ここに回答がありました。
これベースに深掘りします。

The {} here is not parsed as an object, but instead as an empty block (§12.1, at least as long as you're not forcing that statement to be an expression, but more about that later). The return value of empty blocks is empty, so the result of that statement is the same as +[]. The unary + operator (§11.4.6) returns ToNumber(ToPrimitive(operand)). As we already know, ToPrimitive([]) is the empty string, and according to §9.3.1, ToNumber("") is 0.
https://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the

しかし、{} here is not parsed as an objectが意味不明である。Objectぢゃん👊

更に調べてみると、最初のトークンが{のときに、{}は空ブロックになるようです。
それを示す例として、順序が逆の場合はObject扱いされてます。

そして、+[]は0なので、空ブロックと0で0となります。
+はToNumber(ToPrimitive(operand))で実装されており、ToPrimitive([])''であるため、ToNumber('')は0です。

補足: 空配列はオブジェクト型なので、プリミティブ型に変換すると空文字列になります。
[]はfalseなので、空文字なり0なりになるのは理解できると思います。
https://qiita.com/makotoo2/items/9566cebf205ef8b42505

Discussion

ログインするとコメントできます