Why if(key in null); throw exception while for(key in null); does not, it is the language design flaws on it?

StackOverflow https://stackoverflow.com/questions/20854100

  •  23-09-2022
  •  | 
  •  

Question

From a language design perspective, why:

if('k' in null);

TypeError: Cannot use 'in' operator to search for 'k' in null

BUT:

for('k' in null);

prints undefined

in ECMAScript spec:

Is it the language design flaw?

Was it helpful?

Solution

From a design perspective, it's hard to say what the appropriate return value of k in null should be (true is clearly wrong, but false is misleading), but it's easy to say that in the for-in statement, you should just skip the loop.

I don't agree with this decision at all - I think that for (k in null) should throw an error, especially if running in strict mode. But you can see how the difference would arise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top