Reputation: 11
I'm expecting this to output "Failed" but instead it outputs "Excellent", even though the value being compared doesn't match that comparison.
What's wrong with my code?
let grade = 99;
if(140 <= grade <= 150) {
console.log('Excellent');
}
else if(100 <= grade) {
console.log('Very Good');
}
else if(grade < 100) {
console.log('Failed');
}
Upvotes: 1
Views: 55
Reputation: 61
Expression 140 <= grade <= 150
is correct in mathematical form. In js you must write it as 140 <= grade && grade <=150
Upvotes: 0
Reputation: 135
Do it like this. You need to separate two condition which you provided in the first if statement.
let grade = 99;
if(140<= grade && grade <=150){
console.log('Excellent');
}
else if(100<= grade){
console.log('Very Good');
}
else if(grade < 100){
console.log('Failed');
}
Upvotes: 0
Reputation: 6180
If you meant to check whether the grade is between 140 and 150 by 140 <= grade <= 150
then you are doing it the wrong way. This will evaluate 140 <= grade
first, which will return either zero or one, which will then be compared to 150 (and hence will always be smaller). You need to use two separate statements:
if(140 <= grade && grade <= 150) {
...
}
Upvotes: 0
Reputation: 218798
This is not how multiple comparisons are made:
if (140 <= grade <= 150)
In this case the first half would evaluate to true
or false
and the rest would be something like true <= 150
which makes little sense.
Instead, rather than think of it in terms of intuition, think of it in terms of combining logical operations. The two operations you want are:
140 <= grade
grade <= 150
Combine those with the "and" operator:
if (140 <= grade && grade <= 150)
Result:
let grade = 99;
if (140 <= grade && grade <= 150) {
console.log('Excellent');
} else if(100 <= grade) {
console.log('Very Good');
} else if(grade < 100) {
console.log('Failed');
}
Upvotes: 3