return to homepage

Scripts: Javascript

ELSE, IF, FOR, WHILE, DO WHILE Loops

The following shows how to use various types of loops to test conditions and carry out functions only when those conditions are satisfied:

JavScript What this means

= =

is equal to

<=

less than or equal to

>=

greater than or equal to

!=

does not equal

||

OR

&&

AND

if

IF

else {}

ELSE

else if {}

ELSE IF

while() {}

WHILE

for() {}

FOR


'if', 'else' and 'else if' logic:

In text
IF (variable1 = variable2) AND (variable3 does not equal variable4) { do something }
ELSE IF (variable2 = variable4) { do something else }
ELSE { do something else }

In JavaScript:

if (A = = B) && (C != D) { funtion(); }
else if ( B = = C) { anotherFuntion(); }
else { anotherFunction2(); }


'for' loop:

In text
for (i is equal to 0 and i is less than x, increment i by one and loop ) { do something }
Therefore, this function loops through all the values of i between zero and x doing something for each value of i.

In JavaScript:

for(i=0; i< x;i++) { document.write('plop'+i); }


'while' loop:

In text
WHILE (a variable is less than another variable) { do something }

In JavaScript:

while(i<=10) { function(); }


'do while' loop:

In text
do { somehting }
while (e.g. one variable is less than another variable)

The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop until the specified condition becomes true. This loop will always be executed once, even if the condition is false, because the code (something) is executed before the condition is tested.

In JavaScript:

do { function(); }
while { x<= Y }