skip to Main Content

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


  1. The first condition (level < 0.01) is true, as -1 is less than 0.01. So the block for that if statement runs and level 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 since level was modified by the previous if statement.

    In this case, you should switch around the order if statements and make use of else.

    if (level < 0) {
        level = 'b';
    } else if (level < 0.01) {
        level = 'a';
    }
    
    Login or Signup to reply.
  2. 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 of level, the original value of level 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 ifs

    • to test level multiple times, without its value being destroyed

    In 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.

    level = -1;
    if (level < 0.01) {
      output = 'a';
    }
    if (level < 0) {
      output = 'b';
    }
    console.log(output);
    Login or Signup to reply.
  3. @Unmitigated is spot on.

    I just want to iterate a little on

    since level was modified by the previous if statement.

    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.

    const level = -1;
    let result;
    if (level < 0) {
        result = 'b';
    } else if (level < 0.01) {
        result = 'a';
    }
    
    console.log(result)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search