JS: Test is object type

By Xah Lee. Date: . Last updated: .

A value is an object if it is not null and typeof (operator) returns "object" or "function".

const is_object = (x) => (x !== null) && (typeof x === "object" || typeof x === "function");

// s------------------------------
// test

[
 {},
 [],
 /./,
 new Date(),
 function f() {},
 (x) => 3,
 new Set(),
 new Map(),
 new WeakMap(),
 new WeakSet(),
 function* () {},
 (function* () {})(),
 JSON,
 Math,
 Error(),
 new Promise(() => {}),
].forEach((x) => {
 console.assert(is_object(x));
});

[
 null,
 3,
 1,
 Infinity,
 NaN,
 "",
 true,
 undefined,
 Symbol(),
].forEach((x) => console.assert(is_object(x) === false));