4

Is there a difference in performance while doing null checks in below 2 ways -

if (!someObject) {
   // dosomething
}

vs

if (someObject != null) {
   // dosomething
}
3
  • If your question is about performance, why don't you just measure it? Commented Feb 17, 2017 at 20:37
  • @Yousuf Read github.com/rwaldron/idiomatic.js at "4.Conditional Evaluation" Commented Feb 17, 2017 at 20:39
  • @wf9a5m75 Thanks for the link, looks like a good resource. Commented Feb 17, 2017 at 20:49

2 Answers 2

8

!someObject checks for all falsy values.

Not ( empty string, undefined, null, 0, false) - will all pass the condition

where as the first condition only checks for null.

 if (someObject !== null) {
    console.log('falsey');
 }

 someObject = null;      // no message in console
 someObject = '';        // falsey
 someObject = undefined; // falsey
 someObject = 0;         // falsey
 someObject = false;     // falsey

Falsey check

if (!someObject) {
    console.log('falsey');
 }

 someObject = null;      // no message in console
 someObject = '';        // no message in console
 someObject = undefined; // no message in console
 someObject = 0;         // no message in console
 someObject = false;     // no message in console
Sign up to request clarification or add additional context in comments.

5 Comments

Since !someObject is evaluating all truthy values, does it mean it is not as efficient when I need to check only for null's?
Since it is just a simple check, the performance with be negligible for both the cases,
okay, I thought so. My colleague told me it is not efficient, so I was wondering.
@Yousuf Your colleague's concern was probably more a combination of performance as well as your dependence on implicit typecasting to evaluate for a null or undefined value. (I am your colleague)
BTW, Benchmark.js says it's about 16% difference (Chrome, someObject = {}). As long as someObject is not null. In case it's null, second option is faster: jsbench.me/tiizafwdy4
0

to properly check for a null you'd have to write:

  if(!someobject && typeof someobject!== "object") 

Ideally typeof null should not return "object"

The Types and Grammar chapter in You Don't Know JS mentions:

this original bug in JS has persisted for nearly two decades, and will likely never be fixed because there’s so much existing web content that relies on its buggy behavior that “fixing” the bug would create more “bugs” and break a lot of web software.

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.