Saturday, 25 January 2014

java script conditional operator example program

?: (Conditional operator)
The conditional operator is used as a shortcut for standard if statement. It takes three operands.
Syntax
Condition ? expr1 : expr2
Parameters
condition : An expression that evaluates to true or false.
expr1, expr2 : Expressions with values of any types.
If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.
For example
status = (marks >= 30) ? "Pass" : "Fail"
The statement assigns value "Pass" to the variable status if marks is 30 or more. Otherwise it assigns the value of "Fail" to status.

HTML


<head>
<title>Example 13</title>
</head>
<body>
<p id="ex"></p>
<script type="text/javascript" src="example.js"></script>
</body>
</html>

JavaScript

//example.js
var colour, favcol;
colour = window.location.search.substring(1);
favcol = ('green' === colour) ? 'is green.' : 'is not green.';
document.getElementById('ex').innerHTML = colour + favcol;


No comments:

Post a Comment