WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Check If a Value is an Object in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the typeof Operator

You can use the typeof operator to check whether a value is an object or not in JavaScript. But, the typeof operator also returns "object" for null and arrays, so we need to consider that too.

Here's an example which offer a simple solution to this problem:

// Defining a function
function isObject(val) {
    if(typeof val === 'object' && val !== null && Array.isArray(val) === false){
        return true;
    } else {
        return false;
    }
}

// Testing few values    
console.log(isObject({}));  // Prints: true
console.log(isObject({name: "Alice", age: 24}));  // Prints: true
console.log(isObject(new Date()));  // Prints: true
console.log(isObject([1, 2, 3]));  // Prints: false
console.log(isObject(null));  // Prints: false
console.log(isObject("John"));  // Prints: false
console.log(isObject(function(){}));  // Prints: false
console.log(isObject(8));  // Prints: false

See the tutorial on JavaScript Data Types to learn more about data types available in JavaScript.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties