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.

5
  • Why not typeof x == "object" && typeof x != "string"? Commented Sep 5, 2016 at 16:21
  • What @ifvictr just said! Commented Sep 5, 2016 at 16:22
  • 1
    But string objects are objects. Treat them as such and assume that your caller knows not to wrap strings. Commented Sep 5, 2016 at 16:26
  • 1
    @ifvictr: If typeof x == "object" is true, then we already know typeof x != "string" is also true. The value of typeof x isn't going to change after the first comparison. Commented Sep 5, 2016 at 17:45
  • string objects are objects - Yes, a gimmick of the spec. Commented Oct 19, 2016 at 11:38

2 Answers 2

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))
)

Sign up to request clarification or add additional context in comments.

2 Comments

@Bergi : what you mean by frames
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.