DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 on

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 lupu • Edited on

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 Author

Nice! Haven't seen this approach before :)

Classic DEV Post:

caching

Web Caching Explained by Buying Milk at the Supermarket