Going into if wrong

Asked

Viewed 76 times

0

I made this code and expected it to return me 'Jedi Master', but always returns 'Intermediate'. First I had done using switch-case instead of if-lse and it always returned me 'Invalid' (in the case of default).

function experiencia(anos) {
        if (anos <= 1) {
                return 'Iniciante'
        } else if (1 < anos <= 3) {
                return 'Intermediário'
        } else if (3 < anos <= 6) {
                return 'Avançado'
        } else if (anos >=  7) {
                return 'Jedi Master'
        } else {
                return 'Inválido'
        }
};

        var anosEstudo = 7;

        console.log(experiencia(anosEstudo))
  • I would have to build if (years <= 3 && < 1) then? And do you have any idea why to return this case?

  • 1 < anos && anos <= 3. Yes.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

5

This syntax does not make sense, it can make the code much simpler and there correct. You can only do one comparison at a time, if you have to compose two comparisons you have to use an operator || or && as needed, but in that case, you don’t even need.

After you pass the first if It is already certain that the number not less than or equal to 1 then there is no reason to check it again in the second, only taking this part already solves the problem.

The same goes for the if next.

I also advise putting ; at the end of each statement even if you don’t need to, the rule where you can and cannot is confusing, be consistent and maintain readability, always put.

The problem you had is similar to what went wrong in the composite comparison. Javascript is a very permissive language.

I don’t know where you saw this syntax, maybe in Python, which actually works the right way because it’s a compound operator. In its code are two independent operators, I explain.

Your code, in the second if is making the following comparison first, only her:

1 < anos

That expression gives a result false or true, because the relational operator < like everyone else always returning a boolean, carrying one of these two values.

Then he will compare the result of this expression with the rest, so he does so:

(1 < anos) <= 3

Let’s say you did true (your example gives, 1 is less than 7):

(true) <= 3

But this cannot be compared directly. But JS has weak typing and tries to coerce the value into something that can be used, so to compare right the JS does so (the true always worth 1):

1 <= 3

The first operand undergoes conversion to be compatible with the second. Whenever there is a comparison involving a number and a boolean the boolean is converted (specification).

And then the final result is true, so fall for that if. It’s not what I expected.

That’s how it works:

function experiencia(anos) {
    if (anos <= 1) return 'Iniciante';
    else if (anos <= 3) return 'Intermediário';
    else if (anos <= 6) return 'Avançado';
    else if (anos >=  7) return 'Jedi Master';
    else return 'Inválido';
}
console.log(experiencia(7));

I put in the Github for future reference.

  • Thank you very much! I didn’t want to be the most efficient so I wrote it looking for the variable and not directly in the console.log; I ended up putting the 'invalid' option if the input was not a number in a hypothetical case. I also ended up writing in the form of intervals because I thought the program would not know which triggar condition (since, for example, for 2 both 'years <= 3' and 'years <=6' are valid).

  • It makes sense, I changed it. He knows, it’s not random, it’s in sequence.

0

Currently javascript does not support this syntax, it should be done as follows:

   function experiencia(anos) {
    if (anos <= 1) {
            return 'Iniciante'
    } else if (anos > 1 && anos <= 3) {
            return 'Intermediário'
    } else if (anos > 3 && anos <= 6) {
            return 'Avançado'
    } else if (anos >=  7) {
            return 'Jedi Master'
    } else {
            return 'Inválido'
    }
};

A suggested improvement is that with these current conditions the 'Invalid' case will never be executed (if the function is always called with integers), and can be removed.

However it is possible to print the result Inválido. If you call the function in the following way:

experiencia('a')

"Invalid"

That I don’t know if it makes sense to solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.