Testing Type
Prev Chapter 2. JavaScript Basics Next

Testing Type

JavaScript offers a way to test the "type" of a variable. However, the result can be confusing -- for example, the type of an Array is "object".

Example 2.33. Testing the type of various variables

var myFunction = function() {
    console.log('hello');
};

var myObject = {
    foo : 'bar'
};

var myArray = [ 'a', 'b', 'c' ];

var myString = 'hello';

var myNumber = 3;

typeof(myFunction);   // returns 'function'
typeof(myObject);     // returns 'object'
typeof(myArray);      // returns 'object' -- careful!
typeof(myString);     // returns 'string';
typeof(myNumber);     // returns 'number'

if (myArray.push && myArray.slice && myArray.join) {
    // probably an array
    // (this is called "duck typing")
}

jQuery offers utility methods to help you determine whether


Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
Functions Home Scope