Introduction to JavaScript Tutorial
By Neil Williams
2007-11-09
JavaScript Statements G-Z
if and else
Use if
when a simple or compound statement must only be executed if certain
variables are already set to compatible values. The simplest if statement may be a test for division by zero:
a=4;
if (x!=0) {y=a/x;}
else
Use else to catch instances where the preceding if test condition failed. else cannot be used except immediately after the closing } of a valid if statement. In situations where if statements are nested inside other if statements, the else statement will apply to the if statement immediately preceding. Take care to put your else statements beneath the correct } bracket.
a=4;
if (x!=0) {y=a/x;}
else { alert( "Division by zero attempted!" ); }
return
Use return to stop execution of the current function and return control to the calling function/procedure.
function my_func(x,y) {
return (x+y);
}
var sum = my_func(4,8);
The code has been adapted to run from HTML here
In this example, the alert box should show the result as 12.
var
Each variable in a function must be declared using var and optionally, var can be used to initialise the variable. Variables defined outside functions can be declared without var.
x=0;
function my_func(x) {
var y=4;
x+=y;
}
while
Simple loops can use while when the variable is already initialised but the contents of the while loop MUST increment or update the variable(s) in the test condition.
var x=0;
while (x<10) {x++;}
The loop executes repeatedly until the test condition evaluates to
false. The test condition is evaluated before each loop is executed.
Note the difference between for and while test conditions, for loops execute until the test condition is true. while loops execute until the test condition is false.
Tutorial Pages:
»
It's flavours and versions
»
Structure and syntax
»
Data types and objects
»
Functions and operators
»
JavaScript Statements A-F
» JavaScript Statements G-Z
»
JavaScript Events
»
JavaScript Global Properties
»
Javascript code to identify your browser
»
Redirecting the browser once identified
Copyright © Neil Williams
|

|