I'm back to the blog! After so many years it seems that the fire is still there and I felt the need to share little something. Without further rumble, let's jump into one of the situations that I find a lot on the job: checking for null on Javascript.
Here is the kind of code that has caused me much pain:
The intent of this is to only do stuff if shipType has a value. I always try to avoid this piece of code and use something more explicit, even when I know there is no problem with the code now.
But why so picky? Checking for null this way has a few problems. Here is a snippet demonstrating:
Notice how, if the value of shipType is a number and is 0, it is never printed. This kind of bug becomes very common because C# uses integers by default as an underlying type for enums, and 0 is the default value for it.
The reason is that null is a falsy value - if you force it to be evaluated as a boolean it will return false. Falsy values are what allows you to write that syntax in the first place. Well, guess what? 0 is also a falsy value! So is the empty string value "".
So, next time you want to check for null, do so explicitly to avoid these kinds of bugs.
Here is the kind of code that has caused me much pain:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (shipType) | |
do something |
But why so picky? Checking for null this way has a few problems. Here is a snippet demonstrating:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var shipType = undefined; | |
if (shipType) console.log("this is never shown. CORRECT"); | |
shipType = null; | |
if (shipType) console.log("this is never shown. CORRECT"); | |
shipType = "abc"; | |
if (shipType) console.log("This is shown! CORRECT"); | |
shipType = 0; | |
if (shipType) console.log("this is never shown, BUT IT SHOULD"); | |
shipType = ""; | |
if (shipType) console.log("this is never shown, BUT IT SHOULD"); |
The reason is that null is a falsy value - if you force it to be evaluated as a boolean it will return false. Falsy values are what allows you to write that syntax in the first place. Well, guess what? 0 is also a falsy value! So is the empty string value "".
So, next time you want to check for null, do so explicitly to avoid these kinds of bugs.
Comments
Post a Comment