www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript If...Else Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49

We use conditional statements in JavaScript of the form if...else when we want to perform different actions based on different conditions in our code.

In our programs sometimes we need to execute some piece of code depending upon a condition being true and not otherwise. To achieve this in JavaScript we have two constructs available i.e. if and switch. In this lesson we will learn to us the if construct and the switch construct will be discussed in one of the coming lessons.

We use the if statement when we want to execute some code only if a specified condition is true. The syntax of if is as under:

if (condition)
{
//execute this code only if the condition evaluates to true
}

Code example of the if statement follows:

<script type="text/JavaScript">
var day = "friday";
if (day == "friday")
{
document.write("Today is Friday ");
}
</script>

Notice the use of "==" in the if condition above. "==" is one of the several comparison operators available in JavaScript. The above comparison operator checks for the equality of the two operands and returns true only if they are equal and false otherwise.

In the above example the code following the if statement in the { } is executed only if the condition evaluates to true. What if we need to execute some other code if the condition evaluates to false? We use the if...else variation of the if statement in that case. The syntax of if...else statement is as under:

if (condition)
{
//execute this code only if the condition evaluates to true
} else {
//execute this code only if the condition evaluates to false
}

Code example of the if...else statement follows:

<script type="text/JavaScript">
var day = "friday";
if (day == "friday")
{
document.write("Today is Friday ");
} else {
document.write("Today is not Friday ");
}
</script>


Next >>> Lesson No. 8: Comparison Operators







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.