Languages
[Edit]
EN

JavaScript - how to check if value is object?

14 points
Created by:
Root-ssh
99280

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

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join