DEV Community

Keff
Keff

Posted on

Is Value an Object

Little function to check if a value is an object:

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

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

Top comments (5)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

For "plain" object, I rely on

function isObject(val){
  return (
    !!val && 
    typeof val === 'object' && 
    val.constructor === Object  // Or val.toString() === '[object Object]'
  );
}
Collapse
 
ionellupu profile image
Ionel Cristian Lupu • Edited

This won't work for class instances:

class User{}
const user = new User;
isObject(user); //false
Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

This is just what "plain" object is.

Collapse
 
wheatup profile image
Hao

Or abuse JSON.stringify

const isObject = val => JSON.stringify(val).startsWith('{');
Collapse
 
nombrekeff profile image
Keff

Nice! Haven't seen this approach before :)