7

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?

4
  • 4
    Well... it wouldn't be the first Javascript oddity, would it?
    – MaxArt
    Commented Dec 31, 2013 at 8:13
  • 3
    A for loop iterates any keys in whatever you pass it, and the k is a variable. You're instead passing the string 'k' to the for loop, and that doesn't work, and naturally the for loop never iterates if there are no keys, without throwing errors as that would cause a ton of issues, while just using in to look for keys in anything that isn't an object fails, with errors, as it should.
    – adeneo
    Commented Dec 31, 2013 at 8:26
  • @adeneo typeof null = "object", so technically it is looking for keys in an object. Commented Dec 31, 2013 at 8:30
  • @RUJordan nope. The typeof return is a language design oversight, not its behavior. Commented Dec 31, 2013 at 8:37

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.