JavaScript Lesson 7:Conditional Operators

<Lesson 6> [Contents] <Lesson 8>

In this lesson, we will learn how to use conditional operators without using If and Else. Conditional operators let JavaScript program executes certain jobs according to certain conditions.

The syntax of the conditional operator is

Conditional Expression ? Execution 1: Execution 2

The conditional operator comprises three parts, the first part is the conditional expression, the second part is execution 1 and the last part is execution 2. The question mark ? separates the conditional expression and execution 1 whilst the colon: separates execution 1 and execution 2. If the conditional expression is true, then JavaScript will run execution 1 and ignores execution2. However, if the conditional expression is false, then JavaScript will ignore execution 1 and run execution 2. Therefore, the symbol ? and : completely replace If and Else.


Example 7.1

In this example, since the expression x>y is false, JavaScript executes the second action, i.e. to display 20 in the browser.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<script>
x=10
y=20
x>y?document.write(x):document.write(y)

</script>
</body>

Click on Example 7.1 to test it out.

The above example can be rewritten to make it more interactive by prompting the user to enter the values, as shown in Example 7.2

Example 7.2

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<script>
x=window.prompt("Enter first value",0)
y=window.prompt("Enter second value",0)
x>y?document.write(x):document.write(y)

</script>
</body>

Click on Example 7.2 to test it out.


<Lesson 6> [Contents] <Lesson 8>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on Reddit