78

Just curious:

  • 4 instanceof Number => false
  • new Number(4) instanceof Number => true?

Why is this? Same with strings:

  • 'some string' instanceof String returns false
  • new String('some string') instanceof String => true
  • String('some string') instanceof String also returns false
  • ('some string').toString instanceof String also returns false

For object, array or function types the instanceof operator works as expected. I just don't know how to understand this.

[new insights]

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im )
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Newclass = function(){};  // anonymous Constructor function
var Some = function Some(){}; // named Constructor function
(5).is();                     //=> Number
'hello world'.is();           //=> String
(new Newclass()).is();        //=> ANONYMOUS_CONSTRUCTOR
(new Some()).is();            //=> Some
/[a-z]/.is();                 //=> RegExp
'5'.is(Number);               //=> false
'5'.is(String);               //=> true
9
  • you have to use Number.prototype.isPrototypeOf(inp) - your way would also work if done correctly: inp.constructor === Number; it might fail, because constructor is just a property of the prototype and can be overwritten!
    – Christoph
    Jan 23, 2009 at 10:56
  • I'm not sure I understand what you mean with 'can be overwritten'. It doesn't mean I can overwrite the constructor with some other constructor (tried it). Number.prototype.isPrototypeOf(4) returns false by the way, so I can't use that for checking the type of primitive values, am I right?
    – KooiInc
    Jan 23, 2009 at 12:19
  • That was the whole point (primitive !== wrapped primitive)! Checking constructors is dangerous because of obj['constructor'] = ??? works! I'd suggest using my typeOf() function; to treat primitives and wrapped primitives the same, use if(typeOf(x).toLowerCase() === 'string')
    – Christoph
    Jan 23, 2009 at 12:40
  • In my experience assigning anything to Obj.constructor doesn't change its Constructor. As a matter of fact such assignment seems to do nothing at all. ('hellowrld').constructor = Number still returns String with getType.
    – KooiInc
    Jan 23, 2009 at 13:18
  • Tried your typeOf of course and yes, it worked for the primitive types. I wanted 1 function for all types, primitive or not. Will try to break getType, if I can't I suppose it's usable.
    – KooiInc
    Jan 23, 2009 at 13:28

6 Answers 6

74

value instanceof Constructor is the same as Constructor.prototype.isPrototypeOf(value) and both check the [[Prototype]]-chain of value for occurences of a specific object.

Strings and numbers are primitive values, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in regular objects (called 'boxing' in Java).

Also, as you noticed, String(value) and new String(value) do different things: If you call the constructor functions of the built-in types without using the new operator, they try to convert ('cast') the argument to the specific type. If you use the new operator, they create a wrapper object.

new String(value) is roughly equivalent to Object(String(value)), which behaves the same way as new Object(String(value)).


Some more on types in JavaScript: ECMA-262 defines the following primitive types: Undefined, Null, Boolean, Number, and String. Additionally, there is the type Object for things which have properties.

For example, functions are of type Object (they just have a special property called [[Call]]), and null is a primitive value of type Null. This means that the result of the typeof operator doesn't really return the type of a value...

Aditionally, JavaScript objects have another property called [[Class]]. You can get it via Object.prototype.toString.call(value) (this will return '[objectClassname]'). Arrays and functions are of the type Object, but their classes are Array and Function.

The test for an object's class given above works when instanceof fails (e.g. when objects are passed between window/frame boundaries and don't share the same prototypes).


Also, you might want to check out this improved version of typeof:

function typeOf(value) {
    var type = typeof value;

    switch(type) {
        case 'object':
        return value === null ? 'null' : Object.prototype.toString.call(value).
            match(/^\[object (.*)\]$/)[1]

        case 'function':
        return 'Function';

        default:
        return type;
    }
}

For primitives, it will return their type in lower case, for objects, it will return their class in title case.

Examples:

  • For primitives of type Number (eg 5), it will return 'number', for wrapper objects of class Number (eg new Number(5)), it will return 'Number';

  • For functions, it will return 'Function'.

If you don't want to discern between primitive values and wrapper objects (for whatever, probably bad reason), use typeOf(...).toLowerCase().

Known bugs are some built-in functions in IE, which are considered 'Object' and a return value of 'unknown' when used with some COM+ objects.

8
  • @annakata: check ECMA-262 . the types are called Undefined, Null, Boolean, Number, String and Object; doesn't matter what typeof returns...
    – Christoph
    Jan 23, 2009 at 10:25
  • @Christoph - it very much matters since the wrapper objects are uppercase, and the typeofs are lowercase and nothing else is accessible. The convention and practice is therefore to refer to the datatypes in the lowercase as made clear here: developer.mozilla.org/En/JS/Glossary
    – annakata
    Jan 23, 2009 at 10:44
  • @annakata: typeof is broken - its return value has nothing to do with the actual types!
    – Christoph
    Jan 23, 2009 at 10:47
  • Well I guess you're going with the spec and I'm going with the practice, which in this case I think is in the right. I think it's ill-advised to reference the types and the wrapper objects with the same format, but I'll not edit your post further.
    – annakata
    Jan 23, 2009 at 10:52
  • 1
    I contest Strings and numbers are primitive values, not objects and therefore don't have a [[Prototype]] Sample: (new Number(123)).__proto__ == (123).__proto__; // true
    – basarat
    Oct 6, 2014 at 4:27
20

You may try to evaluate:

>>> typeof("a")
"string"
>>> typeof(new String("a"))
"object"
>>> typeof(4)
"number"
>>> typeof(new Number(4))
"object"
3

As stated in Christoph's answer, string and number literals are not the same as String and Number objects. If you use any of the String or Number methods on the literal, say

'a string literal'.length

The literal is temporarily converted to an object, the method is invoked and the object is discarded.
Literals have some distinct advantages over objects.

//false, two different objects with the same value
alert( new String('string') == new String('string') ); 

//true, identical literals
alert( 'string' == 'string' );

Always use literals to avoid unexpected behaviour!
You can use Number() and String() to typecast if you need to:

//true
alert( Number('5') === 5 )

//false
alert( '5' === 5 )
1

In the case of primitive numbers, the isNaN method could also help you.

1

This is a nuance of Javascript which I've found catches some out. The instanceof of operator will always result in false if the LHS is not an object type.

Note that new String('Hello World') does not result in a string type but is an object. The new operator always results in an object. I see this sort of thing:

function fnX(value)
{
     if (typeof value == 'string')
     {
          //Do stuff
     }
}
fnX(new String('Hello World'));

The expectation is that "Do Stuff" will happen but it doesn't because the typeof the value is object.

1

To check if the given number is an instance of Number Class

We need to use the Object Prototype chain.

Object(n) instanceof Number

true if it is a Number, in this case 4.

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.