A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Check If a Value is an Object in JavaScript
Q:

How to Check If a Value is an Object in JavaScript

0

How to Check If a Value is an Object in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now