JavaScript check if object | Example code

  • by

Try using the typeof() method or instanceof method to check if the object is in JavaScript. You can use it with the if statement.

JavaScript check if object

Simple example code: How to check whether a value is an object

instanceof by itself won’t work, because it misses two cases:

// oops:  isObject(Object.prototype) -> false
// oops:  isObject(Object.create(null)) -> false
function isObject(val) {
    return val instanceof Object; 
}

typeof x === 'object' won’t work, because of false positives (null) and false negatives (functions):

// oops: isObject(Object) -> false
function isObject(val) {
    return (typeof val === 'object');
}

Object.prototype.toString.call won’t work, because of false positives for all of the primitives:

> Object.prototype.toString.call(3)
"[object Number]"

> Object.prototype.toString.call(new Number(3))
"[object Number]"

So use:

function isObject(val) {
    if (val === null) { return false;}
    return ( (typeof val === 'function') || (typeof val === 'object') );
}

Or

function isObject(obj) {
  return obj === Object(obj);
}

Source: stackoverflow.com

Complete code

<!DOCTYPE html>
<html>
<body>

  <script>

   function isObject(obj) {
    return obj === Object(obj);
  }

  const test = {};
  if (isObject(test)){
    console.log("Test variable is object")
  }

</script>

</body>
</html> 

Output:

JavaScript check if object
  • Use the instanceof Function
const test = {};
function isObject(val) {
    return val instanceof Object; 
}
console.log(isObject(test));
  • Use the typeof() Function
const test = {};
function isObject(val) {
    return (typeof val === 'object');
}
console.log(isObject(test));
  • Use User-Defined Functions
const test = {};
function t() {};
function isObject(val) {
    if (val === null) { return false;}
    return ( (typeof val === 'function') || (typeof val === 'object') );
}
console.log(isObject(test));
console.log(isObject(t));
  • Use the getPrototypeOf()
const test = {};
function isObject(obj) {
  return obj === Object(obj);
}
function isObject2(obj) {
    return obj.constructor.toString().indexOf("Object") > -1;
}
console.log(isObject(test));
console.log(isObject2(test));

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.