Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: All
May 7, 1999

Shortcut for if-else in JavaScript

JavaScript has C-like syntax. Therefore, it is possible to use the ?: conditional operator, which is a shortcut for the if-else block:
 
Expression?true part:false part
Try this example:
 
<html>
<body>
<script language=javascript>
function foo(){
	(1<2)?alert("1 is less than 2"):alert("1 is not less than 2");
!(1<2)?alert("1 is less than 2"):alert("1 is not less than 2");
}
</script>
<input type=button value="click" onclick="foo()">
</body>
</html>
William Wen
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date