Pages

Monday, 23 April 2012

Javascript Comparison Operators


The comparison operators are used in Javascript to compare values of variables. That means to check if two variables are equal, greater or less than other and some other functions.

List of Comparison Operators

OperatorOperator nameExamples
==Equal (note single = sign is used for assignment, not for comparison)
  • x = 9;
  • if x == 9 (comparison result is true)
  • if x == 18 (This comparison result is false)
!=Not equal to
  • x = 9;
  • if x != 9 (comparison result is false)
  • if x != 18 (This comparison result is True)
===Strict Equal to (not only should match value but also variable type)x = 50;
y = "50";
  • if x == y (comparison result is true as value is same)
  • if x === y ( comparison result is false as although value is same, one variable is numeric type while the other 'y' is string type)
    For details See Lesson on - Javascript variable types
<Less than
  • x = 9;
  • if x < 10 (comparison result is true)
  • if x < 6 (This comparison result is false)
>Greater than
  • x = 9;
  • if x > 10 (comparison result is false)
  • if x > 6 (This comparison result is true)
<=Less than or equal to
  • x = 9;
  • if x <= 10 (comparison result is true)
  • if x <= 9 (This comparison result is also true) Either has to be true, smaller than or equal to. Although x is not less than 9, but it is equal to 9. therefore it is true.
>=Greater than or equal to
  • x = 9;
  • if x >= 10 (comparison result is false)
  • if x >= 6 (This comparison result is true) Either has to be true, greater than or equal to.


Examples of How Comparison operators are practically used.

In the example below, we will enter marks obtained by multiplestudents in the final exams (out of 1000 total marks) and at the backend, javascript code will compare the marks and list the highest marks(largest number) obtained along with the name of the student.
Peter's Final Exam Marks : 

Julie's Final Exam Marks : 

Joey's Final Exam Marks : 

Dont worry now about how the code is working, we will look at that in the later lessons once we get familiar with more basic code writing. If you however wish to see the explanation for the code used in the above example, click here. (expand)

No comments:

Post a Comment

Thank you for your valuable comment