Saturday, April 30, 2011

JavaScript If Statements - XI

When you write code, you will often need to use conditional statements.

A conditional statement refers to a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like.

JavaScript If statements are an example of conditional statements. With If statements, you can tell the browser to execute a piece of code only if a given condition is true.



Example If statement:

The resulting output:

Just like the sky!
Exlanation of code
We first declare a variable called "myColor" and set the value to "Blue". We then use a JavaScript if statement to test if the value of the variable is "Blue". If it is, we output some text to the user.

To create a JavaScript If statement
Start with the word "if"
Between open and closed brackets, write the actual condition that is being tested (i.e. if something is equal to something else).
Between open and closed curly brackets (or braces), specify what will happen if the condition is satisfied.
JavaScript If Else statement
The above code is OK if you only want to display something when the condition is true. But what if you want to display something when the condition isn't true. For example, what if the variable "myColor" was equal to, say, "red"?

This is where an If Else statement comes in handy. The "Else" part is what we're interested in here. The "Else" is what tells the browser what to do if the condition is not true.

Example If Else statement:

The resulting output:

Didn't pick blue huh?
Exlanation of code
The first part of this code is the same as the previous example. The second part is where we specify what to do if the condition is not true. . Therefore, you write "else" followed by what you want to occur, surrounded by curly braces.

Write an if statement (as per first example)
Follow this with the word "else"
Between open and closed curly brackets (or braces), specify what to do next.
JavaScript If Else If statement
The If Else If statement is more powerful than the previous two. This is because you can specify many different outputs based on many different conditions - all within the one statement. You can also end with an "else" to specify what to do if none of the conditions are true.

Example If Else If statement:

The resulting output:

Just like shiraz!
Exlanation of code
We started with an "if" and ended with an "else", however, in the middle, we used an "else if" statement to specify what to do if the "myColor" variable was equal to Red. This statement looks exactly like the "if" statement - just with an "else" prepended to it.

By the way, we could have specified as many "else if" conditions as we liked.

If you do have many "else if" conditions, you might consider using a JavaScript "Switch" statement. The Switch statement is explained in the next lesson.

No comments:

Post a Comment