javascript tutorial - [Solved-5 Solutions] Check if a value is an object in javascript - javascript - java script - javascript array



Problem:

How to check if a value is an Object in JavaScript?

Solution 1:

Try using typeof(var) and/or var instanceof something.

Solution 2:

If typeof yourVariable === 'object', it's an object or null. If we want to exclude null, just make it yourVariable !== null && typeof yourVariable === 'object'.

Solution 3:

Object.prototype.toString.call(myVar) will return:

  • "[object Object]" if myVar is an object
  • "[object Array]" if myVar is an array
  • etc.

Solution 4:

The official underscore.js uses this check to find out if something is really an object

// Is a given variable an object?
_.isObject = function(obj) {
  return obj === Object(obj);
};

click below button to copy the code. By JavaScript tutorial team

Solution 5:

Little late... for "plain objects" (we mean, like {'x': 5, 'y': 7}) we have this little snippet:

function isPlainObject(o) {
   return ((o === null) || Array.isArray(o) || typeof o == 'function') ?
           false
          :(typeof o == 'object');
}
click below button to copy the code. By JavaScript tutorial team

It generates the next output:

console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false
click below button to copy the code. By JavaScript tutorial team

It always works for me. If will return "true" only if the type of "o" is "object", but no null, or array, or function.


Related Searches to javascript tutorial - Check if a value is an object in javascript