0

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.

Walle Cyril
  • 3,087
  • 4
  • 23
  • 55

2 Answers2

4

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))
)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

There are many ways to check type of Object/String/Array.

  • using type of X operator using

  • Object.prototype.toString.apply(X)

    //Its performance is worst

  • Object.getPrototypeOf(X)

  • X.constructor.

Where X can be Object/Array/String/Number or Anything. For performance Comparison Please see below image

enter image description here

Vishnu Shekhawat
  • 1,245
  • 1
  • 10
  • 20