Nothing wrong with it, boolean evaluations in javascript short circuit so if the falsy check fails it'll drop off. You could do optional chaining which is a bit shorter but could be misinterpreted later due to misreading if (mouseY < characters[i - 1]?.handle.position.y) { ... } if characters[i-1] doesn't exist the entire chain will resolve to undefined numberis incompatible with undefined so any comparison to it will resolve to false https://en.wikipedia.org/wiki/Short-circuit_evaluation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining Answer from kherven on reddit.com
🌐
Reddit
reddit.com › r/javascript › [askjs] is it bad practice to check if a value exists in the same if() statement the value is used?
r/javascript on Reddit: [AskJS] Is it bad practice to check if a value exists in the same if() statement the value is used?
December 2, 2023 -

I was making a tool for Dungeons and Dragons in which the user can click and drag character names around the screen. The characters are objects in an array, and whenever the user is dragging the name, an i() statement compares the mouse's position to the name above and the name below in the array. Problem is, the next or previous character in the array might not exist, the index might be out of bounds, and there's no guarantee that it will be in bounds.

if(mouseY < characters[i - 1].handle.position.y) {

So I did this.

if(characters[i - 1] != undefined && mouseY < characters[i - 1].handle.position.y) {

The key is checking the value is not undefined first, because that's how an if() statement is processed. If it is not undefined, the program can proceed to the next check, now that it is safe to do so. If it is undefined, it aborts the if() statement, and so the next check, which would bring everything to a screeching halt, never happens.

I'm just wondering if using if() statements in this way is something people should be doing. It feels like I shouldn't be doing it, but at the end of the day, it works.

Top answer
1 of 6
28
Nothing wrong with it, boolean evaluations in javascript short circuit so if the falsy check fails it'll drop off. You could do optional chaining which is a bit shorter but could be misinterpreted later due to misreading if (mouseY < characters[i - 1]?.handle.position.y) { ... } if characters[i-1] doesn't exist the entire chain will resolve to undefined numberis incompatible with undefined so any comparison to it will resolve to false https://en.wikipedia.org/wiki/Short-circuit_evaluation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
2 of 6
8
As many people have said, readability is your main concern. Is it "bad practice"? Well that's more a people issue than a coding issue. Logically we can write the same code multiple ways and get the same result and have similar performance. The difference you'll run into is you coming back to the project after 6 months of not paying attention to it and depending which option you chose, how fast you'll be able to pick it back up. This results in a few questions: Is this a short term personal project? Then it doesn't really Is this a long term personal project? Then it's a question to you to ask if you were to read this line of code, is it clear to you what's going on? Is this a team project? Readability is far more important for team projects because you never know if a junior engineer or a staff engineer is reading it. So let's start with your code and refactor it a bit. Your current code: if(characters[i - 1] != undefined && mouseY < characters[i - 1].handle.position.y) { Reading this, I have no idea what characters[i - 1] means (pointing to a readability concern) and it's duplicated. We can improve future readability by pulling out a variable: const someMeaningfulName = characters[i - 1]; if(someMeaningfulName != undefined && mouseY < someMeaningfulName.handle.position.y) { This way when someone reads the code, it's far easier to understand your intention when you were writing the code. That variable meant something at the time or writing, it's useful to capture that. Now incorporating @kherven's comment const someMeaningfulName = characters[i - 1]; if (mouseY < someMeaningfulName?.handle.position.y) It definitely reduces the code, and improves readability, but does it improve readability of intention? Your original code checked for undefined and not null. By using this code, if you intentionally wanted to throw an error when the value is null you have just introduced a bug. Fairly sure that's not the case but just calling it out that undefined !== null and to be careful with nullish. Anyways, if I'm reading this code and it doesn't make sense why someMeaningfulName could be nullable, we could increase the code to improve readability: const someMeaningfulName = characters[i - 1]; if (someMeaningfulName == null) { // Some meaningful reason as to why null is being thrown out here return; } if (mouseY < someMeaningfulName.handle.position.y) That said, the last one might be overkill if it's obvious and in that case you can go back to the previous option. Anyways, that's what I would put as my code review comment if I saw this.
🌐
Reddit
reddit.com › r/askprogramming › why is checking to see if a variable exists bad practice? does this matter at all when debugging?
r/AskProgramming on Reddit: Why is checking to see if a variable exists bad practice? Does this matter at all when debugging?
October 6, 2020 -

Trying to get to where my code isnt working I will use an IF statement that looks something like this,

If "foo_var_name" in locals(): #check to see if variable exists

If foo_var_name== 42: #stop at the line I need to look into

Print("look here")

With my debugger stopping on Print.

Ive read this is bad practice, so I'm curious why. That said, I'm only using it for debugging purposes now. Is there any issue here?

Bonus: Why shouldn't I use this in production as logic that executes ONLY if a variable has already been created?

Top answer
1 of 14
28
Wow, I have never ever thought of checking if a variable exists at runtime. So that's something to think about, I guess. I think people just assume that all variables used at some point in the code have been defined earlier. Also, referring to a nonexistent variable is an error in all statically-typed and most dynamically-typed languages, and the logical solution is to define this variable before referring to it, not to execute that code only if that variable has been defined. For me, variable scope is a static property that can be deduced statically: you can look at the code and circle all parts of it where a given variable can be accessed. It's not about runtime. When I create a new variable and then access, even in a dynamic language like Python, I always automatically make sure that I don't access it somewhere where it hasn't been defined. For some reason. Checking if some attribute exists at runtime is fine because code can dynamically create attributes at runtime, so it makes sense to check if hasattr(object, "the_attribute"). But normally code can't generate variables dynamically.
2 of 14
15
You should be able to tell if a variable exists just by reading the code. The linter will tell you if you do it wrong. Writing code that way gives a level of safety, I know that I'm never gonna get a NameError in production. If you have to check it means you're using variables unsafely, by declaring them under an if or using dynamic variable names by messing with the locals dict. Programmers expect variable access to be safe. Even in Python where most things are not safe. It's easy to keep it safe and there's not much benefit breaking it. If you need a value associated to a dynamic name use a dictionary, that's what they are for. Unlike variables, Python programmers expect dictionary access to be unsafe in that you have to use .get or you may get a KeyError. If you have a variable that may or may not have a meaningful value, set it to None first. Or, if None is a valid value, you can use a sentinel object: NOT_SET = object() my_var = NOT_SET if some_condition: my_var = None if my_var is NOT_SET: ... else: ... Ultimately it's tradeoff of dynamicity vs safety, Python is pretty far on the dynamic side but even Python programmers find dynamic variable names to be a bit too far on the unsafe side.
🌐
Reddit
reddit.com › r/learnjavascript › how to properly test that a value exists?
r/learnjavascript on Reddit: How to properly test that a value exists?
November 8, 2016 -

I'm a professional Java developer learning JavaScript. In Java, testing if a variable exists is simple:

if(val != null){
    //Do stuff
}

In JavaScript, however, there is undefined and null. My basic understanding is that undefined means that the variable has not been declared, while null can mean it has no value.

So, to properly test if a value exists, should I always test for both, or what? What are some best practices for this?

Thanks.

🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-check-if-a-variable-exists-or-defined-in-javascript.php
How to Check If a Variable Exists or Defined in JavaScript
<script> var x; var y = 10; if(typeof x !== 'undefined'){ // this statement will not execute alert("Variable x is defined."); } if(typeof y !== 'undefined'){ // this statement will execute alert("Variable y is defined."); } // Attempt to access an undeclared z variable if(typeof z !== 'undefined'){ // this statement will not execute alert("Variable z is defined."); } /* Throws Uncaught ReferenceError: z is not defined, and halt the execution of the script */ if(z !== 'undefined'){ // this statement will not execute alert("Variable z is defined."); } /* If the following statement runs, it will also throw the Uncaught ReferenceError: z is not defined */ if(z){ // this statement will not execute alert("Variable z is defined."); } </script>
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-defined-variable-checking
3 Ways to Check if a Variable is Defined in JavaScript
If the error is caught, that would mean that the variable is not defined: ... missingVar in the above example is not defined. When trying to access the variable in a try block, a ReferenceError error is thrown and catch block catches this reference error. That's another way to check the variable's existence...
Find elsewhere
Top answer
1 of 8
117

A variable is declared if accessing the variable name will not produce a ReferenceError. The expression typeof variableName !== 'undefined' will be false in only one of two cases:

  • the variable is not declared (i.e., there is no var variableName in scope), or
  • the variable is declared and its value is undefined (i.e., the variable's value is not defined)

Otherwise, the comparison evaluates to true.

If you really want to test if a variable is declared or not, you'll need to catch any ReferenceError produced by attempts to reference it:

var barIsDeclared = true; 
try{ bar; }
catch(e) {
    if(e.name == "ReferenceError") {
        barIsDeclared = false;
    }
}

If you merely want to test if a declared variable's value is neither undefined nor null, you can simply test for it:

if (variableName !== undefined && variableName !== null) { ... }

Or equivalently, with a non-strict equality check against null:

if (variableName != null) { ... }

Both your second example and your right-hand expression in the && operation tests if the value is "falsey", i.e., if it coerces to false in a boolean context. Such values include null, false, 0, and the empty string, not all of which you may want to discard.

2 of 8
20

It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,

if (window.variableName)

is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.

That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.

if ( variableName  && typeof variableName !== 'undefined' )
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript check if variable exists
How to Check if Variable Exists in JavaScript | Delft Stack
February 2, 2024 - We can also use the if statement to check if a variable exists because it covers and checks many cases like it checks whether the variable is undefined, null, '', 0, Nan, and false.
🌐
Sentry
sentry.io › sentry answers › javascript › javascript check if variable exists (is defined/initialized)
JavaScript check if variable exists (is defined/initialized) | Sentry
For example, if myVariable is defined as 0 or false, this check will fail. ... const myVariable = 0; if (myVariable) { console.log("myVariable is defined!"); } else { console.log("myVariable is not defined!"); // this line will be printed, even though myVariable is defined above } The expression if (myVariable != null) will produce false positives, as a variable can be defined with the value null.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-check-the-existence-of-variable
JavaScript Check the existence of variable - GeeksforGeeks
July 11, 2025 - To do this, we will use the typeof operator. The typeof operator will return undefined if the variable is not initialized and the operator will return null if the variable is left blank intentionally.
🌐
DEV Community
dev.to › jkvyff › checking-if-a-variable-exists-3pk6
Checking if a Variable Exists - DEV Community
December 14, 2019 - 'exists': 'nope'); // exists console.log(y !== undefined ? 'exists': 'nope'); // nope console.log(z !== undefined ? 'exists': 'nope'); // ReferenceError: z is not defined · Closer, but now we are casting types again, and still doing the comparison that breaks on undeclared variables
🌐
Reddit
reddit.com › r/gamemaker › how to check if a variable hasn't been set, if checking is undefined doesn't work?
r/gamemaker on Reddit: How to check if a variable hasn't been set, if checking is undefined doesn't work?
November 6, 2021 -

Hey there! I'm really sorry for the confusing title but basically I've got code like this:

function example(object)
{
     if object.Owner != undefined
     {
           object.Owner.image_alpha = 0.5
      }
}

The argument I am passing through is a created object. So for example obj_bullet and obj_bullet.Owner would be obj_gun (this isn't exactly what I'm doing but the best way I can explain this

However not every object passed through function(object) will have the Owner set, hence why I added a check for undefined. If I try to pass an object through that does not have .Owner defined, GameMaker crashes with

 Variable <unknown_object>.Owner(100444, -2147483648) not set before reading it.

I've also had this issue before so am I misusing undefined, and is there a different way I can do this?

🌐
LambdaTest Community
community.lambdatest.com › general discussions
How to Check if a Variable Exists and is Initialized in JavaScript - LambdaTest Community
April 22, 2025 - What’s the best way in JavaScript to check if a variable exists and is initialized, regardless of its type? This version keeps the intent intact, flows conversationally, and smoothly includes the keyword javascript check if variable exists.
🌐
TutorialsPoint
tutorialspoint.com › How-can-I-check-whether-a-variable-is-defined-in-JavaScript
How can I check whether a variable is defined in JavaScript?
Users can use above method to check existence of functions and variable declared with the var keyword. Generally, we use the try/catch block to save our code from crashing with an unknown error. The JavaScript returns the reference error when the variable is undefined or uninitialized. We can try to access the variable in the try block, and if any error occurs or the variable is undefined, control goes to the catch block, and we can resolve the error there.
🌐
CodingDeft
codingdeft.com › posts › javascript-check-if-variable-defined
How to check if a variable is defined in JavaScript | CodingDeft.com
Tutorial on how check if a variable is defined, if a property exists in an object, and if a property exists in window.
🌐
Mkyong
mkyong.com › home › javascript › check if variable is exists in javascript
Check if variable is exists in JavaScript - Mkyong.com
August 29, 2012 - Here’s a list of values returned by the typeof operator: ... So, in this case, to check if a variable is exists or defined, use “typeof” operator and check if the returned value is “undefined“.