JS Loops
#
WhyIn JavaScript, loops give us an easy way to do repetitive tasks. There are situations where you have to write a statement or execute a set of logic multiple times or display a message with a slight variation in numbers. There are various situations that are more easily served by one type of loop over the others as we will see later.
#
WhatTypes of JavaScript Loops:
for
- loops through a block of code a number of timesfor/in
- loops through the properties of an objectfor/of
- loops through the values of an iterable objectwhile
- loops through a block of code while a specified condition is truedo/while
- also loops through a block of code while a specified condition is true
We will also cove these keywords:
- The
break
statement - The
continue
statement
for
Loop#
The The for loop will repeat until a specified condition evaluates to false
.
Syntax:
Example:
for
Loop Variations#
for
loops can be written in a variety of ways. If the need arises, you may omit certain syntax.
- Initialization:
- Conditional:
- Increment/Decrement:
for/in
Loop#
The The for/in
statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.
Syntax:
* More examples will be covered with the introduction of objects
for/of
Loop#
The The JavaScript for/of
statement loops through the values of an iterable object. for/of
lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.
Syntax:
* More examples will be covered with the introduction of objects
while
Loop#
The The while
loop will run infinitely until a specified condition is false
. It can run 0 or more times. (if you don’t have a break statement or some way to make the conditional false.. you will crash your browser)
Syntax:
Example:
do/while
Loop#
The The do/while
loop will execute a specified block of code once, then will run until a condition is false. It will run at least 1 time. (be careful of infinite loops)
Syntax:
Example:
break
Statement#
The Use the break statement to terminate a loop.
Example:
#
Takeaways- Loops provide a way to iterate over repetitive tasks
while
,do/while
, andfor
loops are common JS loop structures- While loop conditions are true, the loops iterations will continue