Chapter 5: Relational Operators in JavaScript
5.1 Relational Operators
In chapter 4, we have learned basic
arithmetic operations in JavaScript, this chapter will introduce the more
powerful relational operators. Using relational operators, we could write
decision making procedures using If keyword.
| Relational Operators |
Meaning |
| x==y |
x is equal to y
|
| x!=y |
x is not equal to y
|
| x>y |
x is more than y
|
| x<y |
x is less than y
|
| x>=y |
x is more than or equal to y
|
| x<=y |
x is less than or
equal to y
|
Example:
|
|
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using Comparison Operators </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
var firstNumber,
//declare first variable
secondNumber;
//declare second variable
firstNumber = window.prompt( "Enter first Number:",
"0" );
secondNumber = window.prompt( "Enter second
integer:", "0" );
document.writeln( "<H1>Comparison Output</H1>" );
document.writeln( "<TABLE BORDER = '1' WIDTH =
'100%'>" ); // Creates table
if ( first == second )
document.writeln( "<TR><TD>" + firstNumber + " = " +
secondNumber +
"</TD></TR>" );
// Creates rows and columns
if ( first != second )
document.writeln( "<TR><TD>" + firstNumber + "
Not equal to " + secondNumber +
"</TD></TR>" );
if ( first < second )
document.writeln( "<TR><TD>" + firstNumber + "
< " + secondNumber +
"</TD></TR>" );
if ( first > second )
document.writeln( "<TR><TD>" + firstNumber + "
> " + secondNumber +
"</TD></TR>" );
if ( first <= second )
document.writeln( "<TR><TD>" + firstNumber + "
<= " + secondNumber +
"</TD></TR>" );
if ( first >= second )
document.writeln( "<TR><TD>" + firstNumber + " >= "
+ secondNumber +
"</TD></TR>" );
// Display results
document.writeln( "</TABLE>" );
</SCRIPT>
</HEAD>
<BODY>
<P>Click Refresh (or Reload) to run the script
again</P>
</BODY>
</HTML>
|
Click Testing Page to view the output
<Previous
Chapter> [Back
to HTMLTutorial] <Next Chapter>