if Statement

|

The if statement is used to make decisions in JavaScript. Boolean operators are also discussed in this lesson because they are used in along with if statement.

if Statement
The if statement is one of the most used features of JavaScript. It is basically the same in JavaScript as it is in other programming languages. If you are new to programming, you should spend some time understanding how the if statement works.

You use the if statement in JavaScript to make decisions. The syntax for it is as follows:

if (condition){
statements
}

if keyword identifies this as an if statement. The condition in the parenthesis ( ) is evaluated to determine if true, and if so then the statements inside the curly braces { } are executed, otherwise they are skipped and the programs continues with the first line after if statement.

An optional else statement can be included with if statement as follows:

if (condition){
statements
}
else{
statements
}

In this case, the statements inside of curly brackets { } after the else keyword are executed if the condition of if statement is false.

Boolean Operators
Suppose you wanted the previous script to display a letter grade instead of passed/failed. You would want to display A for a 90 or above, B for a grade 80 or above but less than 90 and ETC. To determine a B you could nest if statements as shown below. This can get real messy and require a lot of code.

if (grade < 90){
if (grade >= 80){
document.write('You got a "B"')
}
}

A better way is to use the and operator, &&. Here is a rewrite of the script using the and operator.

if (grade < 90 && grade >= 80){
document.write('Grade is a "B"')
}

The and operator, && , allows you to combine two conditions so that both must be true to satisfy the if condition. Another Boolean operator is the or operator, ||, which combines two conditions such that the if statement is satisfied if either condition is true. The third boolean operator is the Not Operator, !, which makes a condition that returns true, false and vice versa.

Look again at the above script and notice that phrase 'Grade is a "B"' contains both double quotes and single quotes. This is the way you can put quotes inside of quotes in JavaScript.




 

©2009