I know this works without error:
if (!null) alert(“GOT HERE”);
But this throws an error when I try:
if (!maybeObject) alert(“GOT HERE”);
because maybeObject is not defined. What’s the best way to do a JavaScript if exists check without causing errors?
I’ve been dealing with cross-browser quirks and shared scripts for years, and honestly, the most bulletproof way I’ve found is using typeof
. It doesn’t throw errors even if the variable was never declared:
if (typeof maybeObject !== "undefined" && maybeObject) {
alert("Object exists and is truthy");
}
This pattern has served me well in larger codebases where some variables might not always be loaded. It’s reliable for a safe javascript if exists check and plays nicely in mixed-scope situations.
Yeah, totally agree with Priyada. I’ve been working a lot with modern ES features, and if you’re in a newer codebase (ES2020+), optional chaining makes this even cleaner, especially when you’re checking deeper properties:
if (maybeObject?.property) {
alert("Property exists");
}
No more nested checks or guards — this returns undefined
silently if maybeObject
is undefined, so no errors thrown. It’s a super intuitive way to do a javascript if exists check when working with nested or uncertain objects. Great for team projects where objects might come in partially shaped.
Building on that if you’re in one of those edge-case scenarios where the variable might not be declared at all (like from dynamic scripts or plugins), then I usually reach for a try-catch
. I’ve seen this save entire debugging sessions:
try {
if (maybeObject) {
alert("Exists!");
}
} catch (e) {
alert("maybeObject is not defined");
}
It’s a last-resort kind of thing, but sometimes in browser dev or plugin-heavy environments, it’s the only way to make a javascript if exists check work without crashing your code. Think of it as a seatbelt for unpredictable contexts.