Categories:

JavaScript Kit > JavaScript Reference > JavaScript Statements > Here

JavaScript Statements- Conditonals

Last updated: September 30th, 2004

JavaScript Statements enable you to implement logic, looping, and more within your script.

Related Tutorials

Conditional Statements

Statement Description
if Syntax:

if (expression)
statement

OR:

if (expression){
statement1
statement2
}

if/ else Syntax:

if (expression)
statement1
else
statement2

OR:

if (expression)
statement1
else if (expression2)
statement2
else
statement3

switch
case
break
default:
The "switch" statement lets you easily execute a different statement depending on the value of an expression (label).

Syntax:

switch (expression){
case label1:
statement1
break
case label2:
statement2
break
default: statement3;
}

"break" is an optional statement that tells "switch" to exit should the proceeding statement be executed. "default" allows you to specify the statement to execute if non of the statements above are executed.

An example speaks a thousand words:

Example:

switch (favoritemovie){
case "Titanic":
alert("Not a bad choice!")
break
case "Water World":
alert("No comment")
break
case "Scream 2":
alert("It has its moments")
break
default : alert("No movie was seen")
}

?: "?:", or the Conditional Operator, is a shorthand method for constructing an evaluation, and executing two different assignments depending on the result. The syntax is:

{condition)? iftrue : iffalse

Example:

y=-1
x=(y<0)? 5: 10

x will contain "5" in the above case. Example(s).

return Used inside functions, "return" lets you exit a function and optionally return a value.

Example 1:

function test(a, b)
var c=a*b
return c
}

Example 2:

function whatever(a){
if (a<3)
return
}

Examples

Example 1- Conditional Operator

The Conditional Operator is extremely handy for quickly assigning a different value to a variable depending on the outcome of an evaluation. Here are two examples:

var browser=(navigator.appName.indexOf("Microsoft")!=-1)? "IE" : "Non IE"

You can expand the number of possible values to assign to more than just two. In fact, there is no limit. Observe the below example, which has 3 possible values:

var browser=(navigator.appName.indexOf("Microsoft")!=-1)? "IE" : (navigator.appName.indexOf("Netscape")? "NS" : "Not IE nor NS"

In the 2nd example, "browser" will contain one of 3 possible values depending on the browser maker of the visitor.
Reference List

Partners
Right column

CopyRight 1998-2014 JavaScript Kit. NO PART may be reproduced without author's permission.