3

I have this code:

if(typeof x == 'object')
    return "{"+Object.keys(x)+"}";

It results in (Chrome):

Uncaught TypeError: Object.keys called on non-object 

Can anybody tell me what's going on here? Btw: Firefox does the same.

ps: Don't know what the object is. Firefox debugging failed me.

4
  • Perhaps the answer is here: stackoverflow.com/questions/17319336/… Commented Sep 25, 2013 at 17:48
  • 5
    What's x? Maybe it's null? Commented Sep 25, 2013 at 17:48
  • Is x null? typeof will return object for a null value Commented Sep 25, 2013 at 17:49
  • @JanDvorak: That's probably it. type null is "object", and would cause this exact error :) Commented Sep 25, 2013 at 17:50

1 Answer 1

7

x is most likely null (which is an object). You should explicitly check with if(typeof x === 'object' && x !== null)

Walking through the spec (to explain the logic):

Object.keys: http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.14 reads

If the Type(O) is not Object, throw a TypeError exception.

This Type is Null for null (http://www.ecma-international.org/ecma-262/5.1/#sec-8.2)

typeof: http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3

The table shows that the typeof null is in fact "object"

So in fact null satisfies typeof x === "object" and triggers a TypeError exception

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.