From a language design perspective, why does
if ('k' in 42);
throw a TypeError
exception while
for ('k' in 42);
does not?
I've read the following sections in ECMAScript spec:
Can someone explain the rationale in having such an inconsistency?
Why can't expression 'k' in 42
in if (...)
just evaluate to false
?
Re-read the in section.
If Type(rval) is not Object, throw a TypeError exception.
42 is not an object, it's a number
typeof 42 // 'number'
typeof new Number(42) // 'object'
for-in statement doesn't require an object, in fact it actually converts it to an object
Let obj be ToObject(experValue).
I don't think it's a reason behind this behaviour, it's probably a design flaw(inconsistency)
I believe the key here is the difference between 'operator' (in
) and 'statement' (for-in
). If you check the standard, you'll see that the latter only throw Errors when they're written incorrectly. The with
case, which throws a SyntaxError (!) in the strict mode, is quite telling.
Apparently you cannot guess whether or not for (var x in someExpr)
is written incorrectly unless you evaluate someExpr
first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With