Loops
Loops are a fundamental concept in programming that allow you to execute a block of code multiple times. They are essential for performing repetitive tasks efficiently. JavaScript provides several types of loops to handle different scenarios.
1. The FOR Loop
The for
loop is the most commonly used loop in JavaScript. It repeats a block of code a specified number of times.
Syntax:
Initialization: This expression runs once before the loop starts. It is typically used to initialize a counter variable.
Condition: This expression is evaluated before each iteration of the loop. If it returns
true
, the loop continues. If it returnsfalse
, the loop stops.Increment: This expression is executed at the end of each iteration. It is typically used to update the counter variable.
Example:
In this example, the message "Iteration number: X" will be printed to the console five times, where X
is the current value of i
(from 0 to 4).
2. The WHILE Loop
The while
loop repeats a block of code as long as a specified condition is true
. It is useful when the number of iterations is not known beforehand.
Syntax:
Example:
In this example, the message "Count is: X" will be printed to the console five times, where X
is the current value of count
(from 0 to 4).
3. The DO … WHILE Loop
The do...while
loop is similar to the while
loop, but it guarantees that the block of code will be executed at least once, even if the condition is false
initially.
Syntax:
Example:
In this example, the message "Count is: X" will be printed to the console five times, where X
is the current value of count
(from 0 to 4).
4. The FOR … OF Loop
The for...of
loop is used to iterate over iterable objects (like arrays, strings, etc.). It provides a simpler and more readable way to loop through elements.
Syntax:
Example:
In this example, the names of the fruits will be printed to the console: "apple", "banana", and "cherry".
5. The FOR … IN Loop
The for...in
loop is used to iterate over the properties of an object. It provides a way to access each key in an object.
Syntax:
Example:
In this example, the properties of the person
object will be printed to the console: "name: John", "age: 30", and "city: New York".
Use Case:
Suppose you're building a simple application to display a list of tasks. You might use a loop to iterate over an array of tasks and print each task to the console.
Example:
In this example:
We have an array
tasks
that contains a list of task descriptions.We use a
for
loop to iterate over the array.We use
console.log
to print each task with its corresponding number.
This use case demonstrates how loops can be used to handle repetitive tasks and process collections of data. Understanding loops is essential for building efficient and effective JavaScript programs.
Help us improve the content 🤩
You can leave comments here.
Last updated