読者です 読者をやめる 読者になる 読者になる

light log

学んだこととか

JavaScriptのnull==undefined

メモ。

JavaScriptでは勝手に型変換が起きる==はあんまり使用すべきではないことになってて、代わりに型と値の等価性を判定する===を使用すべきということになってるという認識。

でもnull == undefinedtrueになるのだけは便利なときがあってたまに使う。

で、仕様がちょっと気になってES5仕様の==の辺りを読んだのでメモ。(もうすぐES6出るのかもしれないけど)

11.9.1 The Equals Operator ( == )

The production EqualityExpression : EqualityExpression == RelationalExpression is evaluated as follows:

1. Let lref be the result of evaluating EqualityExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating RelationalExpression.
4. Let rval be GetValue(rref).
5. Return the result of performing abstract equality comparison rval == lval. (see 11.9.3).

左右の値を取り出して、比較自体は11.9.3 の "abstract equality comparison" で行う。

で、11.9.3は

11.9.3 The Abstract Equality Comparison Algorithm

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

1.If Type(x) is the same as Type(y), then
  a. If Type(x) is Undefined, return true.
  b. If Type(x) is Null, return true.
  c. If Type(x) is Number, then
    i. If x is NaN, return false.
    ii. If y is NaN, return false.
    iii. If x is the same Number value as y, return true.
    iv. If x is +0 and y is -0, return true.
    v. If x is -0 and y is +0, return true.
    vi. Return false.
  d. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
  e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
  f. Return true if x and y refer to the same object. Otherwise, return false.
2. Ifx is null and y is undefined, return true.
3. Ifx is undefined and y is null, return true.
4. If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).
5. If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y.
6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
8. If Type(x) is either String or Number and Type(y) is Object,
return the result of the comparison x == ToPrimitive(y).
9. If Type(x) is Object and Type(y) is either String or Number,
return the result of the comparison ToPrimitive(x) == y.
10. Return false.

複雑!

やっぱり使うとしてもnull == undefinedだけでいいかな。

ECMAScript Language Specification - ECMA-262 Edition 5.1