Loops allow you to execute a block of code repeatedly until a certain condition is met. There are several types of loops in JavaScript, including the for
loop, the while
loop, and the do-while
loop.
for loop
Here’s an example of a for
loop in JavaScript:
for (let i = 0; i < 5; i++) { console.log(i); }
In this example, we’ve used a for
loop to log the numbers 0 through 4 to the console. The syntax of a for
loop is for (initialization; condition; increment/decrement) { loop_body }
. The initialization statement is executed before the loop starts, the condition is checked before each iteration, and the increment/decrement statement is executed after each iteration.
while loop
Here’s an example of a while
loop in JavaScript:
let i = 0; while (i < 5) { console.log(i); i++; }
In this example, we’ve used a while
loop to achieve the same result as the previous for
loop example. The syntax of a while
loop is while (condition) { loop_body }
. The loop will continue to execute as long as the condition is true.
do-while loop
Here’s an example of a do-while
loop in JavaScript:
let i = 0; do { console.log(i); i++; } while (i < 5);
In this example, we’ve used a do-while
loop to achieve the same result as the previous while
loop example. The syntax of a do-while
loop is do { loop_body } while (condition)
. The loop will execute at least once, even if the condition is false.
for…in loop
In addition to these basic loops, JavaScript also provides the for...in
loop and the for...of
loop, which are used to iterate over objects and arrays, respectively.
const myObject = { name: "John", age: 30, city: "New York" }; for (let key in myObject) { console.log(key + ": " + myObject[key]); }
In this example, we’ve used a for...in
loop to iterate over the properties of an object and log their values to the console. The syntax of a for...in
loop is for (variable in object) { loop_body }
.
for…of loop
Here’s an example of a for...of
loop:
const myArray = ["apple", "banana", "orange"]; for (let fruit of myArray) { console.log(fruit); }
In this example, we’ve used a for...of
loop to iterate over the elements of an array and log their values to the console. The syntax of a for...of
loop is for (variable of iterable) { loop_body }
.
Leave a Reply