You are on page 1of 11

JavaScript (Loop

Statement)
Sungchul Lee
Outline
➢Loop statement
❑For/while/do-while statement
❑For/In
❑For/Of
Loop statement
➢Loops are handy, if you want to run the same code over and
over again, each time with a different value.
➢JavaScript loops
❑for - loops through a block of code a number of times
❑for/in - loops through the properties of an object
❑for/of - loops through the values of an iterable object
❑while - loops through a block of code while a specified
condition is true
❑do/while - also loops through a block of code while a
specified condition is true
For loop
➢Loops through a block of code a number of times
❑Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
❑Statement 1 is executed (one time) before the execution of
the code block.
❑Statement 2 defines the condition for executing the code
block.
❑Statement 3 is executed (every time) after the code block
has been executed.
While Loop
➢The while loop loops through a block of code as long as a
specified condition is true.
❑Syntax: Start
while (condition) {
// code block to be executed
} Condition
False

True

Statements
Stop
Do/While Loop
➢This loop will execute the code block once, before checking if
the condition is true, then it will repeat the loop as long as the
condition is true.
❑Syntax:
Start
do {
// code block to be executed
} Statements
while (condition);
True

Stop Condition
False
For/In Loop
➢for/in statement loops through the properties of an object:
❑Normally, used the for/in loop with enumerable objects
❑Syntx:
for (variable in enumerable) {
// code block to be executed
}
❑Example:
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
for (const key in person) {// index or key
text += person[key];
}
Practice 1
Key-Value
pair
➢for (const index in person)
❑Access key/index on
person object
➢person[index]
❑Access the value
❖Like hash
For/Of Loop
➢for/of statement loops through the values of an iterable objects
❑Arrays, Strings, Maps, NodeLists and more
❑Syntax:
for (variable of iterable) {
// code block to be executed
}
❑Example:
var person2 = ["John", "Doe", 25];
var text2 = "";
for (const value of person2) {// index or key
text2 += value;
}
Practice 2
➢for(const value of person2)
❑Access value on person2
❑Access one by one
Summary
➢Loop statement
❑For/while/do-while statement
❑For/In
❖for (variable in enumerable) { // variable will be key or index
// code block to be executed
}

❑For/Of
for (variable of iterable) {// variable will be value in objects
// code block to be executed
}

You might also like