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 Ternary (?) Operator 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

The ? Operator, also called the ternary operator is an efficient and easy to use way for doing if...else tests in JavaScript.

With the help of the ternary operator we can reduce a multi-line if...else statement to a single line of code.

The use of the ternary (?) operator is very simple. First we write an expression to be evaluated followed by the ? symbol. Then we write the code to be executed if the expression evaluates to true followed by the : character and then the code to be executed if the expression evaluates to false.

Example code follows:

<script type="text/JavaScript">
var number = 10;
document.write(
number <= 7 ?
" number is less than or equal to 7 " :
" number is greater than 7 ");

</script>

The above code has been broken up into several lines for readibility and the same could also be written on a single line.

In the above example code a ternary operator has been used to test and print whether the variable number is less than or equal to 7.

Next >>> Lesson No. 39: JavaScript Bitwise Operators





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