How to check a not-defined variable in JavaScript
To check for undeclared or undefined variables, use the typeof operator:
The typeof operator will not trigger a ReferenceError if myVar is not declared, making it a safe option.
Practical techniques for checking variable definition
In current JavaScript versions, strict comparison (===) is your best bet for avoiding misconceptions when checking for undefined.
Since ECMAScript 5, undefined is read-only and can't be reassigned, making undefined comparisons fail-proof.
Testing for "truthiness" and property existence
Talking about truthiness, or the truth-value of a variable, provides a brevity advantage:
However, beware! This trick can be double-edged, as it will fail for any falsy values like 0, null, false, or an empty string.
Property existence in objects can be verified using the handy in operator:
Foolproof methods to prevent ReferenceErrors
To handle potential undeclared variables, use the tried-and-true try/catch structure:
Notice the console.warn instead of alert: it's easier on the eyes and better for debugging. UX matters, even in console logs!
Handling undefined the smart way: Best practices
Confucius says, "Your code is your garden. Tend to it with care." 🌼 Here are some tips for maintaining a blooming codebase:
- Clear and concise naming - Choose variable names that speak not whisper.
- Durability - Stick to a consistent technique for variable checks across your application to avoid confusion and bugs.
- Be proactive - Don’t wait for a
ReferenceErrorto happen. Make sure a variable exists before you use it.
The different shades of non-existence
JavaScript has quite an array in store when it comes to non-existing values: undefined, null, 0, false and "" (empty string). Each one of these has its unique use.
Especially true when dealing with the DOM, where null is the go-to value when something is not found whereas in the actual JS, undefined carries the flag.
Meaningful error messages
Consider this your PSA: Error messages should be a beacon of guidance, not a source of confusion.
Was this article helpful?