loading...

Is Value an Object

nombrekeff profile image Manolo Edge ・1 min read

Little function to check if a value is an object:

function isObject(val){
  return (
    val != null && 
    typeof val === 'object' && 
    Array.isArray(val) === false
  );
}

Notice that Date, RegExp, etc.. will pass the check.

Discussion

pic
Editor guide
 

For "plain" object, I rely on

function isObject(val){
  return (
    !!val && 
    typeof val === 'object' && 
    val.constructor === Object  // Or val.toString() === '[object Object]'
  );
}
 

This won't work for class instances:

class User{}
const user = new User;
isObject(user); //false
 

This is just what "plain" object is.

 

Or abuse JSON.stringify

const isObject = val => JSON.stringify(val).startsWith('{');
 

Nice! Haven't seen this approach before :)