Search code examples
javascriptlogical-operatorscomparison-operators

Javascript: Why use Logical Operators along with Comparison Operator?


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?


Solution

  • 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.