Why (3).constructor is valid while “constructor” in (3) is not valid?
-
28-09-2019 - |
Question
(3).constructor
is Number, but "constructor" in (3)
is TypeError, why?
Solution
With using the property accessor, the number 3
is turned into an object of Number. And an object of that type has a constructor and thus an constructor
property.
But as ChaosPandion already pointed out, the in
operator requires the right expression to yield an object but 3
is not an object but a plain number literal.
OTHER TIPS
The specification for the in
operator explains this. Specifically, see step 5 of semantic evaluation.
11.8.7 The in operator
The production RelationalExpression : RelationalExpression in ShiftExpression is evaluated as follows:
- Let lref be the result of evaluating RelationalExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating ShiftExpression.
- Let rval be GetValue(rref).
- If Type(rval) is not Object, throw a TypeError exception.
- Return the result of calling the [[HasProperty]] internal method of rval with argument ToString(lval).
The reason (3).constructor
works is a a bit more challenging to understand but essentially when you use the dot operator on a reference with a primitive base it gets lifted into an object.