Walle Cyril Walle Cyril - 3 months ago 8
Javascript Question

How to check if x is an Object but not a String Object

What I have so far.

const isNotNullObject = function (x) {
return (typeof x === "object" && x !== null);
};


It works fine for arrays and objects. But for String objects too !

isNotNullObject(String(5))
false
isNotNullObject(new String(5))
true


What I want is false for any type of string. Note that I don't have control of the calling code. I can't remove
new
myself. I need a solution that does not create a new String just to check for equality if possible for performance reasons.

Answer

Use instance of

return (typeof x === "object" && !(x instanceof String) && x !== null)

const isNotNullObject = function(x) {
  return (typeof x === "object" && !(x instanceof String) && x !== null);
};

console.log(
  isNotNullObject(String(5)),
  isNotNullObject(new String(5))
)