In JavaScript, there are several ways to loop through arrays and objects. Here's an overview of the for, for..of, and for..in loops:
forloop:
The basic for loop is used to iterate over a range of numbers or indices in an array.
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
Example:
for (let i = 0; i < 10; i++) {
console.log(i);
}
for..ofloop:
The for..of loop is used to iterate over the values of an iterable object, such as an array or a string.
Syntax:
for (variable of iterable) {
// code to be executed
}
Example:
const arr = ['apple', 'banana', 'orange'];
for (const fruit of arr) {
console.log(fruit);
}
Output:
apple banana orange
for..inloop:
The for..in loop is used to iterate over the properties of an object, such as the keys in a key-value pair.
Syntax:
for (variable in object) {
// code to be executed
}
Example:
const person = {
name: 'John',
age: 30,
gender: 'male'
};
for (const prop in person) {
console.log(`${prop}: ${person[prop]}`);
}
Note that this line console.log(`${prop}: ${person[prop]}`); is using a Template Literal
Output:
name: John age: 30 gender: male