I’m making a code to change the value of something based on the range it is in. I notice that there’s an inconsistency when using decimals and negative numbers which is a must in my application.
But at least, i wanted to share this problem to check if this is common knowledge and i’m missing something.
level = -1;
if (level < 0.01) {
level = 'a';
}
if (level < 0) {
level = 'b';
}
console.log(level);
Expected result: ‘b’
Result: ‘a’
Removing negative numbers seems to no change anything, changing the float number to an int number doesn’t change anything also. It seems that if the first "if clause" is validated, the second one is skipped for some reason.
3
Answers
The first condition (
level < 0.01
) is true, as-1
is less than0.01
. So the block for thatif
statement runs andlevel
is set to'a'
.The next condition (
level < 0
) is equivalent to'a' < 0
, which is false. It is not skipped; it is just that the condition no longer matches sincelevel
was modified by the previousif
statement.In this case, you should switch around the order if statements and make use of
else
.The order of your "if"s matters
I think you have been unwise to modify the input variable, rather than generate a new output variable.
Once your first
if
changes the value oflevel
, the original value oflevel
is no longer available to be tested.One fix would be to reverse the order of the "if" statements. However that does not fix the fundamental problem: confusing the input and output variables.
It would be better to have separate input and output variables
This allows you:
to keep your original ordering of
if
sto test
level
multiple times, without its value being destroyedIn general separating input and output variables is a good plan. Separating variables of different types is also a good plan. So this arrangement is good from both points of view.
@Unmitigated is spot on.
I just want to iterate a little on
General rule is to avaoid reassigning variables and use const for variables. In your case value can be a number or a letter. Meaning you have no idea what you are working with. You also use multiple if statements instead of if else, meaning both can trigger.