Iterating Over Arrays:
const items = ['Item 1', 'Item 2', 'Item 3'];
function ItemList() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
Processing Object Properties:
const user = { name: 'Alice', age: 25, city: 'Wonderland' };
function UserDetails() {
return (
<div>
{Object.keys(user).map((key) => (
<p key={key}>{key}: {user[key]}</p>
))}
</div>
);
}
Handling Asynchronous Data:
async function fetchData() {
const response = await fetch('<https://api.example.com/data>');
const data = await response.json();
data.forEach(item => {
console.log(item);
});
}
fetchData();
Complex Iteration Logic:
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
console.log(`${numbers[i]} is even`);
}
}
Understanding the different types of for
loops and their appropriate uses is essential for effective JavaScript programming, especially when working with data manipulation and rendering in React.