How to check for an undefined or null variable in JavaScript?
The double equals (==
) check for both undefined
and null
. This is the equivalent of killing two birds with one stone due to type coercion.
Using strict equality for declared variables
Strict equality for the win
Strict equality checking (===
) is a verbose but clear-cut method of checking.
Nullish coalescing: A modern touch
The nullish coalescing operator (??
) injects a default value when dealing with null
or undefined
. It's like a first aid kit for variables!
Logical nullish assignment aka new kid on the block
The logical nullish assignment (??=
) in ES2020 allows assigning to variables only if they are null
or undefined
. The code is cleaner and efficient. Less is more, right?
Special care for undeclared global variables
The safety net of typeof
When handling undeclared global variables, typeof
check ensures that no exception is thrown. It's safer than a seatbelt in JavaScript terms!
Property checking: The 'in' operator
The in
operator acts like a magnifying glass for object property check, avoiding errors.
Avoiding the landmines of JavaScript checking
The unequal danger of loose inequality
The loose inequality (!=
) can lead to unwanted scenarios. Consider this as a -1/10, would not recommend.
Dangerously simplistic: The 'if (variable)'
The simplistic truthy check can risk errors with falsy values and should be used with caution.
Understanding the full context
The playing field isn't level
Remember, the behavior of null/undefined checks may change depending on the JavaScript environment. JavaScript likes to stay unpredictable!
Allowing 'eqnull' to the club
Tools like JSHint with the eqnull
option can tolerate == null
for comparisons, like a friendly bouncer.
A trip to the library sometimes helps
In-depth knowledge can come from MDN Web Docs, authoritative sources like JavaScript specification, or respected publications. Remember, knowledge is power!
Was this article helpful?