Loops in JavaScript
Introduction Link to heading
Loops in JavaScript allow you to execute a block of code multiple times. They are a fundamental tool for automating repetitive tasks and processing data collections.
Types of loops Link to heading
- for: Used to execute a block of code a certain number of times.
- for/in: Used to cycle through the properties of an object.
- for/of: Used to loop through the values of an iterable object.
- while: Used to execute a block of code while a condition is met.
- do/while: Used to execute a block of code at least once and then as long as a condition is met.
Example: Link to heading
const students = ["Maria", "Sergio", "Rosa", "Daniel"];
// Function to greet each student
function greetStudents(student) {
console.log(`Hello, ${student}`);
}
// Using a for loop to iterate over the students array
for (var i = 0; i < students.length; i++) {
greetStudents(students[i]);
}
// Using a for/of loop to iterate over the students array
for (var student of students) {
greetStudents(student);
}
// Using a while loop to remove and greet each student
while (students.length > 0) {
var student = students.shift();
greetStudents(student);
}
Explanation: Link to heading
- The
for
loop loops through thestudents
array and calls thegreetStudents
function for each element. - The
for/of
loop is a more concise way to loop through thestudents
array and invokes thegreetStudents
function for each element. - The
while
loop removes the first element from thestudents
array and calls thegreetStudents
function until the array is empty.
Keep learning about loops to write more efficient and automated JavaScript code!