Javascript: Comparison Operators
So now that we can use if statements and the "is equal to" operator ('==') to compare two values to check if they are exactly equal to eachother (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 that's where the magic of comparison operators comes in! Instead of having to use the '==' operator, we can use any of a few that are available by default in Javascript.
As well as "is equal to" ('=='), we also have "is greater than" ('>'), "is greater than or equal to" ('>='), "is less than" ('<'), "is less than or equal to" ('<=') and "is not equal to" ('!='). Note that for obvious reasons, the greater and less than based ones are only going to work properly with numbers.
These are all pretty self explanatory (and probably didn't really need their very own tutorial), so let's just write a simple script which gets input from the user and then does some checks on it:
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?');
}
else
{
alert('Your number bores me.');
}
Notice 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.
Back to Javascript

