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.
If a variable is declared but no value has been assigned to it, then its type would be "undefined." The same type would be assigned to variables that haven't been declared. In that case, how would we check if a variable has been declared?
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?
You want the typeof operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
The typeof operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
I've seen so many methods; but I am looking for a simple style I can adopt in my code to keep it consistent:
if (PostCodeInformation !== null PostCodeInformation !== undefined){
}
So this is a really stupid question but here goes. I want to return one thing if a variable exists and has a value and another thing if it doesn't.
zebra ? 4 : 3
As you can see here I'm checking if there is a **zebra** variable that is defined and has a value. If it exists, the console will return **4**. Otherwise, it will return 3. Clearly, such a variable does not exist, so I expected to see **3**.
Instead I'm greeted with this message.
Uncaught ReferenceError: zebra is not defined
Sorry but I do not understand :(
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.
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 variableNamein 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.
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' )
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?