Saturday, February 2, 2013

instanceof & typeof Operators

Sometimes, even if it is considered bad habit, we need to check the class of an object in JavaScript. Classes may be defined by the programmer, but I will cover this topic later, for now let's just focus on classes defined by the interpreter. There are many, for example:
  • Object
  • String
  • Number
  • Date
  • Function
  • ...
To check if an object is an instance of a specific class, JavaScript offers the instanceof method, which may be used in the following way:

var mynmbr = new Number(1);
var mystrng = new String("disasterjs!");
var myfunc = function(){
    console.log("hello world!");
}
mynmbr instanceof Number //returns true
mynmbr instanceof Object //returns true
mystrng instanceof String //returns true
mystrng instanceof Object //returns true
mynmbr instanceof String //returns false
myfunc instanceof Function //returns true

Be careful when using instanceof about what you are checking. For example numbers and strings not wrapped in the constructor are treated as primitive value, thus a call for instanceof in that case would produce an unexpected result:


var mystrng = "disasterjs!";
var mynmbr = 1;

mynmbr instanceof Number //returns false
mynmbr instanceof Object //returns false
mystrng instanceof String //returns false
mystrng instanceof Object //returns false

What about the typeof operator? This operator returns the class as a string. The following table summarises its possible return values:

Type
Result
Undefined"undefined"
Null"object"
Boolean"boolean"
Number"number"
String"string"
Host object (provided by the JS environment)Implementation-dependent
Function"function"
E4X XML object"xml"
Any other object"object"

Programmer may be careful here when checking a Null object as the result of a typeof will return "object". Here are a couple of examples on how to use typeof.


typeof 1 === "number" //true
typeof Number(1) === "number" //true
typeof 1 === "object" //false
typeof undefined_variable === "undefined" //true
typeof true === "boolean" //true


And that's it.
Categories:

0 comments:

Post a Comment