Week4-JS-Web Programming
Week4-JS-Web Programming
CONDITIONAL
LOGICAL
WEB ENGINEERING
TOPICS:
IF .. ELSE IF.. ELSE
WHILE, DO WHILE LOOP
SWITCH
Loops: while and for
We often need to repeat actions.
For example, outputting goods from a list one after another or just running the same code for
each number from 1 to 10.
This article covers only basic loops: while, do..while and for(..;..;..).
If you came to this article searching for other types of loops, here are the pointers:
while (condition) {
// code
// so-called "loop body"
}
While the condition is truthy, the code from the loop body is executed.
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
alert( i );
i++;
}
Loops: while and for
The “while” loop
The while loop has the following syntax:
while (condition) {
// code
// so-called "loop body"
}
While the condition is truthy, the code from the loop body is executed.
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
alert( i );
i++;
}
Loops: while and for
A single execution of the loop body is called an iteration. The loop in the example above makes
three iterations.
If i++ was missing from the example above, the loop would repeat (in theory) forever. In
practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can
kill the process.
Any expression or variable can be a loop condition, not just comparisons: the condition is
evaluated and converted to a boolean by while.
Loops: while and for
For instance, a shorter way to write while (i != 0) is while (i):
let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
alert( i );
i--;
}
Loops: while and for
The “do…while” loop
The condition check can be moved below the loop body using the do..while syntax:
do {
// loop body
} while (condition);
The loop will first execute the body, then check the condition, and, while it’s truthy, execute it
again and again.
Loops: while and for
For example:
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
This form of syntax should only be used when you want the body of the loop to execute at least
once regardless of the condition being truthy. Usually, the other form is preferred: while(…)
{…}.
The “for” loop
The for loop is more complex, but it’s also the most commonly used loop.
Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ ...
That is, begin executes once, and then it iterates: after each condition test, body and step are
executed.
If you are new to loops, it could help to go back to the example and reproduce how it runs step-
by-step on a piece of paper.
The “for” loop
Here’s exactly what happens in our case:
// run begin
let i = 0
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// ...finish, because now i == 3
Breaking the loop
Normally, a loop exits when its condition becomes falsy.
But we can force the exit at any time using the special break directive.
For example, the loop below asks the user for a series of numbers, “breaking” when no number
is entered:
let sum = 0;
while (true) {
let value = +prompt("Enter a number", '');
if (!value) break; // (*)
sum += value;
}
alert( 'Sum: ' + sum );
Breaking the loop
The break directive is activated at the line (*) if the user enters an empty line or cancels the
input. It stops the loop immediately, passing control to the first line after the loop. Namely,
alert.
The combination “infinite loop + break as needed” is great for situations when a loop’s
condition must be checked not in the beginning or end of the loop, but in the middle or even in
several places of its body.
Continue to next iteration
The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it
stops the current iteration and forces the loop to start a new one (if the condition allows).
We can use it if we’re done with the current iteration and would like to move on to the next one.
alert(i); // 1, then 3, 5, 7, 9
}
Continue to next iteration
For even values of i, the continue directive stops executing the body and passes control to the
next iteration of for (with the next number). So the alert is only called for odd values.
if (i % 2) {
alert( i );
}
}
Continue to next iteration
From a technical point of view, this is identical to the example above. Surely, we can just wrap
the code in an if block instead of using continue.
But as a side effect, this created one more level of nesting (the alert call inside the curly braces).
If the code inside of if is longer than a few lines, that may decrease the overall readability.
The "switch" statement
A switch statement can replace multiple if checks.
It gives a more descriptive way to compare a value with multiple variants.
The syntax: The switch has one or more case blocks and an optional default.
let a = 2 + 2;
switch (a) {
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
case 5:
alert( 'Too big' );
break;
default:
alert( "I don't know such values" );
}
The "switch" statement
Here the switch starts to compare a from the first case variant that is 3. The match fails.
Then 4. That’s a match, so the execution starts from case 4 until the nearest break.
If there is no break then the execution continues with the next case without any checks.
User input
The prompt() method displays a dialog box that prompts the user for input.
The prompt() method returns the input value if the user clicks "OK", otherwise it returns null.
User input
let text;
let favDrink = prompt("What's your favorite cocktail drink?");
switch(favDrink) {
case "Coca-Cola":
text = "Excellent choice! Coca-Cola is good for your soul.";
break;
case "Pepsi":
text = "Pepsi is my favorite too!";
break;
case "Sprite":
text = "Really? Are you sure the Sprite is your favorite?";
break;
default:
text = "I have never heard of that one!";
}
End of Week 7
Learn more and
Keep Safe!