Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why if('k' in 42); throw exception while for('k' in 42); does not, in javascript?

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:

  • 11.8.7 The in operator
  • 12.6.4 The for-in Statement

Can someone explain the rationale in having such an inconsistency?

Why can't expression 'k' in 42 in if (...) just evaluate to false?

like image 779
aztack Avatar asked Dec 20 '13 11:12

aztack


2 Answers

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)

like image 132
Silviu Burcea Avatar answered Sep 20 '22 13:09

Silviu Burcea


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.

like image 29
raina77ow Avatar answered Sep 21 '22 13:09

raina77ow