0

Why do we use logical operators along with comparison operators? I'm still quite new to coding, whenever my lecturers gave us some example they always write like this:

if (totalMark >= 0 && totalMark < 40) {
  finalGrade = "F";
  document.getElementById("final_grade").value = finalGrade;
  }

Why not just use comparison operator?

if (0 <= totalMark < 40) {
  finalGrade = "F";
  document.getElementById("final_grade").value = finalGrade;
  }

Is there any advantages of using one over the other or is it just the same?

0

4 Answers 4

2
if (0 <= totalMark < 40) {

This doesn't do what you think it does. You're expecting it to check whether totalMark is in the range from [0, 40). But what it's really going to do is evaluate it one piece at a time. It's going to check 0 <= totalMark and get either a true or a false.

Let's say totalMark is a negative number, so you get false from this piece. The next thing it will compare is false < 40. That doesn't make much sense, but javascript will do its best. Following the obscure rules of javascript type coercion, false gets treated as 0 so it checks 0 < 40 which is true. Therefore, 0 <= totalMark < 40 resolves to true when totalMark is a negative number. In fact, if you walk through the other possibilities, it will always result in true.

In short, these comparison operators can only look at 2 things at once. And then you use &&'s and ||'s to build up something larger.

Sign up to request clarification or add additional context in comments.

Comments

0

Because the second one is not working how you think it does.

With the second one, only 0<=x condition is checked first. If that is true the second part does not matter.

let x = 20;
if(0 <= x < 40) { console.log("yo2"); }
if(0 <= x < 10) { console.log("yo"); }

Comments

0

The comparison 0 <= totalMark < 40 doesn't work as you would expect.

It first computes 0 <= totalMark (assuming totalMark = 10) which becomes true. Then it compares true < 40. Here it casts true to a number and 1 < 40 becomes true.

Therefore it feels more like random behaviour, than the comparison you wanted. For instance you can try following example:

const totalMark = 10

if (0 < totalMark < 20) console.log('0 < ... < 20')
if (20 > totalMark > 5) console.log('20 > ... > 5')

Comments

0

0 <= totalMark < 40 checks whether totalMark is in the interval [0, 40) in some languages — such as CoffeeScript and Python — but not JavaScript (as explained in other answers).

Indeed, you can see that CoffeeScript compiles this code to the JavaScript code 0 <= totalMark && totalMark < 40.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.