Languages
[Edit]
EN

JavaScript - how to check if value is object?

14 points
Created by:
Root-ssh
175460

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!

 

In the below code shows how to check if value is object.

Custom method

Object function example

// 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

 

typeof operator example

// ONLINE-RUNNER:browser;

function isObject(value) {
    if (value == null) {  // null or undefined
        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

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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