L3
L3
JavaScript supports a compact set of statements, specifically control flow statements, that you can use
to incorporate a great deal of interactivity in your application. Any JavaScript expression is also a
statement.
Block statement
The most basic statement is a block statement, which is used to group statements. The block is
delimited by a pair of curly braces:
JS
{
statement1;
statement2;
// … statementN;
}
Example
Block statements are commonly used with control flow statements (if, for, while).
JS
while (x < 10) {
x++;
}
Conditional statements
A conditional statement is a set of commands that executes if a specified condition is true. JavaScript
supports two conditional statements: if...else and switch.
if...else statement
Use the if statement to execute a statement if a logical condition is true. Use the optional else clause
to execute a statement if the condition is false. An if statement looks like this:
JS
if (condition) {
statement1;
}
else
{
statement2;
}
Here, the condition can be any expression that evaluates to true or false. If condition evaluates to
true, statement1 is executed. Otherwise, statement2 is executed. statement1 and statement2 can be
any statement, including further nested if statements.
You can also compound the statements using else if to have multiple conditions tested in sequence, as
follows:
JS
if (condition1) { statement1;
} else if (condition2) { statement2;
} else if (conditionN) { statementN; }
else { statementLast; }
In the case of multiple conditions, only the first logical condition which evaluates to true will be
executed. To execute multiple statements, group them within a block statement ( { /* … */ } ).
In general, it's good practice to always use block statements—especially when nesting if statements:
JS
if (condition) {
// Statements for when condition is true
// …
} else {
// Statements for when condition is false
// …
}
Example
In the following example, the function checkData returns true if the number of characters in a Text
object is three. Otherwise, it displays an alert and returns false.
JS
function checkData() {
if (document.form1.threeChar.value.length === 3) {
return true;
}
else {
alert(`Enter exactly three characters. ${document.form1.threeChar.value} is not valid.`, );
return false;
}
}
switch statement
A switch statement allows a program to evaluate an expression and attempt to match the expression's
value to a case label. If a match is found, the program executes the associated statement.
A switch statement looks like this:
JS
switch (expression) {
case label1: statements1;
break;
case label2: statements2;
break;
// …
default:
break statements
The optional break statement associated with each case clause ensures that the program breaks out of
switch once the matched statement is executed, and then continues execution at the statement
following switch. If break is omitted, the program continues execution inside the switch statement
Example
In the following example, if fruitType evaluates to "Bananas", the program matches the value with
case "Bananas" and executes the associated statement. When break is encountered, the program exits
the switch and continues execution from the statement following switch. If break were omitted, the
statement for case "Cherries" would also be executed.
JS
switch (fruitType) {
case "Oranges":
console.log("Oranges are $0.59 a pound."); break;
case "Apples":
console.log("Apples are $0.32 a pound."); break;
case "Bananas":
console.log("Bananas are $0.48 a pound."); break;
case "Cherries":
console.log("Cherries are $3.00 a pound."); break;
case "Mangoes":
console.log("Mangoes are $0.56 a pound."); break;
case "Papayas":
console.log("Papayas are $2.79 a pound."); break;
default:
console.log(`Sorry, we are out of ${fruitType}.`);
}
console.log("Is there anything else you'd like?");
There are many different kinds of loops, but they all essentially do the same thing: they repeat an
action some number of times. (Note that it's possible that number could be zero!)
The various loop mechanisms offer different ways to determine the start and end points of the loop.
There are various situations that are more easily served by one type of loop over the others.
The statements for loops provided in JavaScript are:
for statement
do...while statement
while statement
labeled statement
break statement
continue statement
for...in statement
for...of statement
for statement
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to
the Java and C for loop. A for statement looks as follows:
JS
Example
In the example below, the function contains a for statement that counts the number of selected options
in a scrolling list (a <select> element that allows multiple selections).
The for statement declares the variable i and initializes it to 0 . It checks that i is less than the number
of options in the <select> element, performs the succeeding if statement, and increments i by 1 after
each pass through the loop.
JS
function countSelected(selectObject) {
let numberSelected = 0;
for (let i = 0; i < selectObject.options.length; i++)
{ if (selectObject.options[i].selected)
{
numberSelected++;
}
} return numberSelected;
}
This function countSelected takes a select element (like a dropdown or multi-select box) as a
parameter and counts how many options are selected. Here's how it works:
1. It initializes a counter numberSelected to 0
2. It loops through all options in the select element using a for loop from 0 to
selectObject.options.length
3. For each option, it checks if it's selected using the selected property
4. If an option is selected, it increments the counter using numberSelected++
5. Finally, it returns the total count of selected options
do...while statement
The do...while statement repeats until a specified condition evaluates to false. A do...while statement
looks as follows:
JS
Statement is always executed once before the condition is checked. (To execute multiple statements,
use a block statement ( { } ) to group those statements.) If condition is true , the statement executes
again. At the end of every execution, the condition is checked. When the condition is false, execution
stops, and control passes to the statement following do...while .
Example
In the following example, the do loop iterates at least once and reiterates until i is no longer less than
5.
JS
let i = 0;
do { i += 1;
console.log(i);
}
while (i < 5);
while statement
A while statement executes its statements as long as a specified condition evaluates to true . A while
statement looks as follows:
JS
If the condition becomes false, statement within the loop stops executing and control passes to the
statement following the loop. The condition test occurs before statement in the loop is executed. If the
condition returns true, statement is executed and the condition is tested again. If the condition returns
false, execution stops, and control is passed to the statement following while. To execute multiple
statements, use a block statement ({ } ) to group those statements.
Example 1
The following while loop iterates as long as n is less than 3:
JS
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the
following values:
After the first pass: n = 1 and x = 1
After the second pass: n = 2 and x = 3
After the third pass: n = 3 and x = 6
After completing the third pass, the condition n < 3 is no longer true , so the loop terminates.
Example 2
Avoid infinite loops. Make sure the condition in a loop eventually becomes false — otherwise, the
loop will never terminate! The statements in the following while loop execute forever because the
condition never becomes false:
JS
labeled statement
A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For
example, you can use a label to identify a loop, and then use the break or continue statements to
indicate whether a program should interrupt the loop or continue its execution. The syntax of the
labeled statement looks like the following:
JS
label: statement
The value of label may be any JavaScript identifier that is not a reserved word. The statement that you
identify with a label may be any statement. For examples of using labeled statements, see the examples
of break and continue below.
break statement
Use the break statement to terminate a loop, switch , or in conjunction with a labeled statement.
When you use break without a label, it terminates the innermost enclosing while, do-while, for,
or switch immediately and transfers control to the
following statement.
When you use break with a label, it terminates the specified labeled statement.
The syntax of the break statement looks like this:
JS
let x = 0; let z = 0;
labelCancelLoops: while (true) {
console.log("Outer loops:", x);
x += 1; z = 1;
while (true) {
console.log("Inner loops:", z);
z += 1;
if (z === 10 && x === 10) {
break labelCancelLoops; }
else if (z === 10) { break;
}
}
}
Continue statement
The continue statement can be used to restart a while , do-while , for , or label statement.
When you use continue without a label, it terminates the current iteration of the innermost
enclosing while, do-while, or for statement and continues execution of the loop with the next
iteration. In contrast to the break statement, continue does not terminate the execution of the loop
entirely. In a while loop, it jumps back to the condition. In a for loop, it jumps to the increment-
expression.
When you use continue with a label, it applies to the looping statement identified with that label.
The syntax of the continue statement looks like the following:
JS
continue;
continue label;
Example 1
The following example shows a while loop with a continue statement that executes when the value of
i is 3. Thus, n takes on the values 1, 3, 7, and 12.
JS
let i = 0; let n = 0;
while (i < 5) {
i++;
if (i === 3) {
continue; }
n += i;
console.log(n);
}
If you comment out the continue the loop would run till the end and you would see 1,3,6,10,15 .
Example 2
The code has two nested while loops with labels checkIandJ and checkJ, and uses a continue statement
with a label.
A statement labeled checkIandJ contains a statement labeled checkJ . If continue is encountered, the
program terminates the current iteration of checkJ and begins the next iteration. Each time continue
is encountered, checkJ reiterates until its condition returns false . When false is returned, the remainder
of the checkIandJ statement is completed, and checkIandJ reiterates until its condition returns false .
When false is returned, the program continues at the statement following checkIandJ .
If continue had a label of checkIandJ , the program would continue at the top of the checkIandJ
statement.
JS
let i = 0; let j = 10;
checkIandJ: while (i < 4) { console.log(i); i += 1;
checkJ: while (j > 4) { console.log(j); j -= 1;
if (j % 2 === 0) {
continue checkJ; }
console.log(j, "is odd.");
}
console.log("i =", i);
console.log("j =", j);
}