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
forloop loops through thestudentsarray and calls thegreetStudentsfunction for each element. - The
for/ofloop is a more concise way to loop through thestudentsarray and invokes thegreetStudentsfunction for each element. - The
whileloop removes the first element from thestudentsarray and calls thegreetStudentsfunction until the array is empty.
Keep learning about loops to write more efficient and automated JavaScript code!