JS Loops
Why#
In 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.
What#
Types 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
breakstatement - The
continuestatement
The for Loop#
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:
The for/in Loop#
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
The for/of Loop#
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
The while Loop#
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:
The do/while Loop#
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:
The break Statement#
Use the break statement to terminate a loop.
Example:
Takeaways#
- Loops provide a way to iterate over repetitive tasks
while,do/while, andforloops are common JS loop structures- While loop conditions are true, the loops iterations will continue