Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  153] [ 1]  / answers: 1 / hits: 19924  / 8 Years ago, thu, july 28, 2016, 12:00:00

Although there are semantic differences between JavaScript's null and undefined, many times they can be treated as the same. What's the preferable way of checking if the value is either null or undefined?






Right now I'm doing the following:



if (typeof value === undefined || value === null) {
// do something
}


Which is pretty verbose. I could, of course, create a function for this and import everywhere, but I'm wishing that there's a better way to achieve this.



Also, I know that



if (value == null) {
}


Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.


More From » node.js

 Answers
1

Also, I know that



if (value == null) {
}


Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.




No, it gets the job done 100% of the time. The only values that are == null are null and undefined. 0 == null is false. == undefined is false. false == null is false. Etc. You're confusing == null with falsiness, which is a very different thing.



That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write value == null or the explicit one you're currently using (or if (value === undefined || value === null)) is a matter of style and in-house convention. But value == null does do what you've asked: Checks that value is null or undefined.



The details of == are here: Abstract Equality Comparison.


[#61214] Tuesday, July 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
estefanib

Total Points: 508
Total Questions: 104
Total Answers: 83

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;