Loops | Bondar Academy
Course: JavaScript for Testers
Module: JavaScript Fundamentals
Instructor: Artem Bondar
Lesson Summary
In this lesson, we explore loops in JavaScript, a mechanism that allows repeating operations multiple times based on a condition. We will cover the most common types of loops used in programming. Basic Loop Structure The basic syntax for a loop starts with the for keyword, followed by parentheses that define three statements: Initial Statement: This initializes a variable (e.g., i = 0 ). Condition: This determines how long the loop runs (e.g., i < 5 ). Increment Statement: This updates the variable after each iteration (e.g., i++ ). The loop body contains the code to execute, such as printing a message. Example of a For Loop To print "hello world" five times, you can use the following for loop: for (let i = 0; i < 5; i++) { console.log("hello world"); } Iterating Over Arrays To loop through an array, such as a list of cars, we can use the for...of loop: for (let car of cars) { console.log(car); } This will print each car in the array. Breaking Out of Loops To stop a loop early, you can use the break statement. For example: if (car === "Toyota") { break; } Using forEach Method Another way to iterate through arrays is by using the forEach method with fat arrow syntax : cars.forEach(car => { console.log(car); }); Summary The for loop is used for repeating operations. The for...of loop is ideal for iterating through arrays. The forEach method provides a compact way to loop through arrays. Thank you for watching, and see you in the next lesson!