Is there a difference in performance while doing null checks in below 2 ways -
if (!someObject) {
// dosomething
}
vs
if (someObject != null) {
// dosomething
}
Is there a difference in performance while doing null checks in below 2 ways -
if (!someObject) {
// dosomething
}
vs
if (someObject != null) {
// dosomething
}
!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
someObject = {}). As long as someObject is not null. In case it's null, second option is faster: jsbench.me/tiizafwdy4to 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.