JavaScript: Comparison Operators

So now you should be able to use 'if' statements and the "is equal to" operator (==) to compare two values to check if they are exactly equal to each other (or if they are unequal since we can use 'else'). But wouldn't it be nice if we could compare things in different ways?

Well this is where the magic of comparison operators comes in! It turns out that == isn't the only comparison operator on the block, we can actually use and of the number that are available in JavaScript! There are a bunch of these which can be seen in the following list:

  • == - Is equal to
  • != - Is not equal to
  • > - Is greater than
  • < - Is less than
  • >= - Is greater than or equal to
  • <= - Is less than or equal to

These are all pretty self explanatory and so the easiest way to show you these is to create a basic script from them. Take, for example, the following:

var userInput = prompt('Enter a number');
if(userInput > 9000)
	alert('It\'s over 9000!');
else if(userInput < 0)
	alert('Why did you specify a negative number?');
	alert('Your number bores me.');

Firstly, note that when we wanted to use an apostrophe inside of a string that we created using single quotes, we did what's called 'escaping' a character by putting a backslash before it. This means that instead of ending the single-quote string, we are in fact putting a single-quote (or apostrophe) into the string itself. Secondly, note that the usage of the comparison operators to form an expression works exactly the same as with the == operator (so no need to worry!). The JSFiddle for this code snippet is below.

The best way to get learn about all these operators and when they're useful is really just to try them out. I suggest just trying to create different applications that require some certain logic functionality and seeing where you get to - if you're stuck for ideas, try creating a basic script in which a student can enter their mark on a test out of 100 and the script uses alert to tell them which letter grade they got ('A', 'B'... 'F', etc.)