18

In the below code :-

 var x = { } ;
    console.log(typeof x);             // o/p is object
    console.log(x instanceof Object ); //o/p is true

If I use "object" instead of "Object" in the last line I get an error.Why is that so when the o/p of second line is object with a lowercase "o"?

3
  • JavaScript is case-sensitive... The name of the constructor is Object, not object. Commented Oct 2, 2012 at 18:46
  • 2
    typeof doesn't return the constructor that was used to create the instance, it simply returns a few predefined values depending on what argument it was used with. Commented Oct 2, 2012 at 18:47
  • 1
    For example typeof "" returns 'string', but there is no string object defined unless you define one. Commented Oct 2, 2012 at 18:48

3 Answers 3

19

Because there's no such thing as an 'object'. Typeof doesn't give you the class back - it gives you back the primitive type that it is. For example, typeof "string" gives you back "string".

The 'Object' is a constructor for an object 'primitive' - so a new Object gives you back an 'object' to work with.. but don't expect to be able to create a 'new object', as an 'object' doesn't exist as a constructor.

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

Comments

9

You get an error because you haven't defined a variable named object. Attempting to read a variable that has not been declared is a ReferenceError.

The Object variable is native to the environment, and is pre-defined as the constructor function for plain objects. That's why it works when you do instanceof Object. Every native object in JavaScript is an instance of Object.

Comments

6

Javascript is case sensitive "object" is essentially a variable that can hold anything. "Object" is an actual javascript type.

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.