Beware When Comparing null
Today I got an issue when somehow the data was not displaying. It was because the data is 0 and unfortunately the code said something like this: if score ? score : "" ; looks correct, right? But we got a mistake that in some programming language like javascript / php 0 will be automatically converted to false and the score 0 will never displaying.
Another consideration is when we play some code in Javascript, we often need to check if a variable is empty or uninitialized. The common values that pop up in these cases are null and undefined. While this seems straightforward, if we’re not careful, this check can introduce bugs that are tough to track down.
Here is the difference between null and undefined with the simple explanation:null is like a box you’ve intentionally emptied and labeled “empty.” You know the box exists, but you’ve deliberately put nothing in it. You’ve assigned it an “empty” value.
undefined is like a box you’ve created but haven’t put anything in yet. You haven’t decided what to put in it, or you simply forgot. The value is undefined.
While they both signify the absence of a value, the key difference is intent. null is an intentional assignment, whereas undefined is the default state of a variable that hasn’t been given a value yet.
let a = null; // we set as null
let b; // undefined
Another case when we do comparison; Javascript has loose equality and Strict equality operator
== (Double Equals): Abstract Equality Operator / Loose Equality Operator
- This operator performs a loose equality comparison.
- It checks for equality after performing type coercion. This means if the operands are of different types, JavaScript attempts to convert them to a common type before making the comparison.
- For example,
42 == '42'evaluates totruebecause the string'42'is coerced into the number42before the comparison.
=== (Triple Equals): Strict Equality Operator
- This operator performs a strict equality comparison.
- Both the value and the data type of the operands must be the same for the comparison to return
true. - For example,
42 === '42'evaluates tofalsebecause, even though the values are numerically equivalent, their types (number and string) are different.
function isEmpty(value: any) {
return value == null;
}
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty(0)); // false
console.log(isEmpty("")); // false
While using == null to check for both null and undefined might seem handy, it’s a double-edged sword.
It works because of type coercion, a feature in JavaScript that tries to convert values to a common type before comparison. When you use ==, JavaScript sees null and undefined as equal.
However, this convenience comes with a risk. If your code later needs to specifically handle null (an intentional empty value) differently from undefined (a variable that was never assigned), using == null will hide that distinction. This can lead to subtle bugs that are hard to debug, especially in larger applications or when working with APIs that return null for specific reasons.
For robust, predictable code, it’s generally better to use the strict equality operator (===). This operator doesn’t perform type coercion, so it will only return true if both the value and the type are the same. This forces you to be explicit in your checks:
myVar === nullchecks for a specifically assignednullvalue.myVar === undefinedchecks for an uninitialized variable.
Being explicit with === makes your code’s intent clearer and prevents unexpected behavior. for me, it is a best practice that helps avoid bugs and makes the code more maintainable.
Okay so here is my note for my future 😀
1. Stick with Strict Equality (===)
Always use === instead of == for comparisons. The strict equality operator checks for both value and type, so null will never equal undefined. This prevents bugs caused by JavaScript’s automatic type coercion and makes your code’s intent crystal clear.
if (value === null): For when you’re specifically checking for a deliberately “empty” value.if (value === undefined): For when you’re checking for a variable that has not yet been assigned.
This distinction is crucial and will save you from a lot of head-scratching later on.
2. Use the Nullish Coalescing Operator (??)
When you need to provide a default value for a variable, use ?? instead of ||.
??(Nullish Coalescing Operator): Only provides the fallback value if the variable isnullorundefined.||(Logical OR Operator): Provides the fallback if the variable isnull,undefined,0,""(an empty string), orfalse.
The ?? operator is a safer choice because it doesn’t treat meaningful “falsy” values like 0 or an empty string as a reason to fall back to a default, sample code:
// Example: Using || can lead to unexpected behavior
let count = 0;
let userCount = count || 5; // userCount becomes 5, not 0!
// Example: Using ?? is more reliable
let count = 0;
let userCount = count ?? 5; // userCount remains 0, as intended
3. Embrace TypeScript’s strictNullChecks
If you’re using TypeScript, enable the strictNullChecks option in your tsconfig.json file. This is a game-changer. It forces you to explicitly handle cases where a variable could be null or undefined, preventing those pesky runtime errors before your code even runs. TypeScript will throw a compile-time error if you try to use a variable that might be null or undefined without first checking it.
Okay, the last but not least, always be mindful when handling null and undefined. Hopefully, this article help to write cleaner and safer code. Happy coding and keep learning!


