Languages
[Edit]
EN

JavaScript - how to check if value is object?

14 points
Created by:
Root-ssh
6417

The first important thing is what is primitive type in JavaScript?

Primitive type literals:

  • 012-4NaN, +Infinity, -Infinity, etc.
  • 'abc', '', etc.
  • true / false
  • undefined
  • null -  special case, but we treat it as not defined object too

Everything else is object type!

Below code shows how to check if value is object.

1. Custom method examples

1.1. With Object function

// ONLINE-RUNNER:browser;

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

// Usage example:

console.log( isObject(null)       ); // false
console.log( isObject(undefined)  ); // false
console.log( isObject(false)      ); // false
console.log( isObject(true)       ); // false
console.log( isObject(0)          ); // false
console.log( isObject(1)          ); // false
console.log( isObject(NaN)        ); // false
console.log( isObject(+Infinity)  ); // false
console.log( isObject('')         ); // false

console.log( isObject([ ])                 ); // true
console.log( isObject({ })                 ); // true
console.log( isObject(function(){ })       ); // true
console.log( isObject(new Number(1))       ); // true
console.log( isObject(Object.prototype)    ); // true
console.log( isObject(Object.create(null)) ); // true

1.2. With typeof operator

// ONLINE-RUNNER:browser;

function isObject(value) {
    if (value === null) { // special case
      return false;
    }
  
  	var type = typeof value;
    
  	return type === 'function' || type === 'object';
}

// Usage example:

console.log( isObject(null)       ); // false
console.log( isObject(undefined)  ); // false
console.log( isObject(false)      ); // false
console.log( isObject(true)       ); // false
console.log( isObject(0)          ); // false
console.log( isObject(1)          ); // false
console.log( isObject(NaN)        ); // false
console.log( isObject(+Infinity)  ); // false
console.log( isObject('')         ); // false

console.log( isObject([ ])                 ); // true
console.log( isObject({ })                 ); // true
console.log( isObject(function(){ })       ); // true
console.log( isObject(new Number(1))       ); // true
console.log( isObject(Object.prototype)    ); // true
console.log( isObject(Object.create(null)) ); // true

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.