Equality and Relational Operators
- = = != //be careful with = =
- < > <= >=
- Boolean expressions: not, and, or
! && ||
- Precedence revisited
Conditional Programming
- Not sequential
- When needed to choose between two (or more) alternatives
- IF syntax
for single statements
if ( condition )
statement;
- examples of Javascript code
if ( input_num < 0 )
document.write ( "Error message<br>");
- IF syntax for multiple statements
if ( condition )
{
statement1;
statement2;
}
- examples of Javascript code
if ( grade == 100 )
{
document.write(
"Excellent job<br>");
bonus = 1;
}
IF-ELSE syntax
- single statements
if ( condition )
statement;
else
statement;
- examples of Javascript code
if (x < 0 )
document.write( "negative number<br>");
else
document.write( "non-negative number<br>");
- Nested IFs
- More than two possible actions
- Second if can be nested inside of the 1st "if" part or the 1st "else" part
- Examples
if ( x <0 )
document.write( "negative number<br>");
else
if ( x == 0 )
document.write( "zero<br>");
else
document.write( "positive number<br>");
ELSE IFs
if (x < 0 )
document.write( "negative number<br>");
else if (x == 0)
document.write( "zero<br>");
else
document.write(" "positive number<br>");
Multi-way selection: The Switch statement
- Used in place of if-elseif-elseif…
- Syntax
switch ( variable)
{
case1: statements;
break;
case2: statements;
break;
. . .
casen: statements;
break;
default: statements;
}