Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Week4-JS-Web Programming

The document discusses different types of loops in programming including while, do-while, for, and switch statements. It provides examples and explanations of how each loop works, when to use different loops, and how to break or continue within a loop. Key points include: - The while loop repeats code while a condition is true - do-while ensures code runs at least once before checking the condition - for loops have initialization, condition, and increment sections to control the loop - break and continue can alter normal loop execution by stopping or skipping to the next iteration - switch statements provide an alternative to chained if/else if for comparing a value against multiple options

Uploaded by

Ryan Obligar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Week4-JS-Web Programming

The document discusses different types of loops in programming including while, do-while, for, and switch statements. It provides examples and explanations of how each loop works, when to use different loops, and how to break or continue within a loop. Key points include: - The while loop repeats code while a condition is true - do-while ensures code runs at least once before checking the condition - for loops have initialization, condition, and increment sections to control the loop - break and continue can alter normal loop execution by stopping or skipping to the next iteration - switch statements provide an alternative to chained if/else if for comparing a value against multiple options

Uploaded by

Ryan Obligar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

OPERATORS

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.

Loops are a way to repeat the same code multiple times.

The for…of and for…in loops


A small announcement for advanced readers.

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:

See for…in to loop over object properties.


See for…of and iterables for looping over arrays and iterable objects.
Otherwise, please read on.
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.

For instance, the loop below outputs i while i < 3:

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.

For instance, the loop below outputs i while i < 3:

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.

It looks like this:

for (begin; condition; step) {


// ... loop body ...
}
Let’s learn the meaning of these parts by example. The loop below runs alert(i) for i from 0 up
to (but not including) 3:

for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2


alert(i);
}
The “for” loop
part
Executes once upon
begin let i = 0
entering the loop.
Checked before every
condition i<3 loop iteration. If false,
the loop stops.
Runs again and again
body alert(i) while the condition is
truthy.
Executes after the body
step i++
on each iteration.
The “for” loop
The general loop algorithm works like this:

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:

// for (let i = 0; i < 3; i++) alert(i)

// 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.

The loop below uses continue to output only odd values:

for (let i = 0; i < 10; i++) {

// if true, skip the remaining part of the body


if (i % 2 == 0) continue;

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.

The continue directive helps decrease nesting


A loop that shows odd values could look like this:

for (let i = 0; i < 10; i++) {

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.

It looks like this:


switch(x) {
case 'value1': // if (x === 'value1')
...
[break]
case 'value2': // if (x === 'value2')
...
[break]
default:
...
[break]
}
The "switch" statement
The value of x is checked for a strict equality to the value from the first case (that is, value1)
then to the second (value2) and so on.
If the equality is found, switch starts to execute the code starting from the corresponding case,
until the nearest break (or until the end of switch).
If no case is matched then the default code is executed (if it exists).
The "switch" statement
An example of switch (the executed code is highlighted):

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!

You might also like