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 the students array and calls the greetStudents function for each element.
  • The for/of loop is a more concise way to loop through the students array and invokes the greetStudents function for each element.
  • The while loop removes the first element from the students array and calls the greetStudents function until the array is empty.

Keep learning about loops to write more efficient and automated JavaScript code!

<< Switch statements in JavaScript Constructor functions in JavaScript >>