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.
I would have to build if (years <= 3 && < 1) then? And do you have any idea why to return this case?
– GheistLycis
1 < anos && anos <= 3
. Yes.– Luiz Felipe
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).
– Maniero