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'); }
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'); }
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) {
...
}
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'); }
Expression 140 <= grade <= 150
is correct in mathematical form. In js you must write it as 140 <= grade && grade <=150
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.