JavaScript Kit > JavaScript Reference > JavaScript Statements > Here
JavaScript Statements- Conditonals
JavaScript Statements enable you to implement logic, looping, and more within your script.
Related Tutorials
- Understanding basic arrays and loops
- Variable and expression shortcuts
- The switch statement of JavaScript1.2
- JavaScript and OOP
- Creating custom objects in JavaScript
Conditional Statements
Statement | Description |
---|---|
if | Syntax: if (expression) OR: if (expression){ |
if/ else | Syntax: if (expression) OR: if (expression) |
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){ "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){ Note: If no break statement is specified inside any of your switch statements, the interpreter will execute the first matching statement block it encounters (obviously), but then proceed to execute any reminding statement blocks following that, regardless of whether the value inside the expression matches, until it encounters another break statement. So in the following code:
var grade = "A" All 4 alerts will be triggered. |
?: | "?:", 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 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) Example 2: function whatever(a){ |
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.- JavaScript Operators
- JavaScript Statements
- Global functions
- JavaScript Events
- Escape Sequences
- Reserved Words