Home / Advanced JavaScript Tutorials / Variable and expression shortcuts

 

 

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS

-Free applets
-Web Tutorials
-Link to Us!

- CSS Drive
- PHP Resources
- Hotels & Vacations
- Bad credit cards
- JavaScript Menus

 

Red_CurlyC035.gif (995 bytes) The "?" conditional expression statement

Finally, let me show you a shortcut technique for compressing those often-used if-else statements. A default if-else statement spans four lines, like below:

<script>
if (navigator.appName=="Netscape")
alert("Netscape user!")
else
alert("IE user!")
</script>

The "?" conditional statement allows you to compact that into just one line, and has the following syntax:

(condition) ? doiftrue : doiffalse

Let's shove our four line code into the compression chamber, shall we?

(navigator.appName=="Netscape") ? alert("Netscape user!")  : alert("IE user!")

The "?" conditional expression statement is being used more and more these days as scripts get longer and longer, and compactness actually becomes an issue. Some people argue against using the "?" statement, saying it's not as "intuitive" as the if-else statement. I say, get intuitive!

-Tutorial introduction
-Declaring many variables at once
-Assignment operator shortcuts
-The "with" statement
-The "?" conditional expression statement

.
End of tutorial

http://javascriptkit.com
Copyright © 1997-2005 JavaScript Kit. NO PART may be reproduced without author's permission.