For simplicity reasons I don’t want to define a variable on top of the script. I thought in the past I could do something like below, but that doesn’t seem to work anymore because I get the error variable is not defined. Is there a way to do this?
if (variable === null) {
variable = notNull;
}
if (variable === undefined) {
variable = notUndefined;
}
Here you define it first and that is also not what I want. I just want to check in the if statement if the variable exist and if not I want to define it. Also I want to make it not exist again on another place in my script.
If you don’t define it, it’s a global variable when you assign a value to it.
From what you have written, it is best to define to variable in the scope you want it in (eg the script instance) and set it to null until you assign a value to it and set it to null after you are done with it.
I’m not entirely sure what you are really looking to do here. Maybe a mini project can help?
I try to find a way to keep all code that is needed for a function on the same place in the *update function, that is reason one. Reason two is that I want to use the two situations (defined and undefined) as a state in my game. Define it in the scope like you write above will overwrite the variable if it was already defined I guess?
Script.prototype.update = function (dt) {
if (variable) {
// Variable is defined, this is a specific state in game and that is why I don't want to define it before
}
else if (!variable) {
// Variable is not defined, this is also a specific state in game and that's why I want to define it here
}
};
Or using this is also fine.
Script.prototype.update = function (dt) {
if (this.variable) {
// Variable is defined, this is a specific state in game and that is why I don't want to define it before
}
else if (!this.variable) {
// Variable is not defined, this is also a specific state in game and that's why I want to define it here
}
};
Script.prototype.initialize = function() {
this.variable = null;
};
Script.prototype.update = function (dt) {
if (this.variable !== null) {
// Variable is defined, this is a specific state in game and that is why I don't want to define it before
} else {
// Variable is not defined, this is also a specific state in game and that's why I want to define it here
}
};
The reason for this is that null and undefined are not the same in JS. Clearing defining it as null in initialize will save some potential headache.
You can, it’s just not recommended because you would have to check against null and undefined.
if (!this.variable) {
console.log('hello');
}
The log will print if this.variable is 0, false, null, undefined and ''
Setting it to a known state such as null means you only have to check against null and makes the code simpler.
Edit: In theory, you can not define it and later set it to undefined and only check against undefined in the if statement. It’s just not recommended from a style point of view.