For...of Loops
When iterating over an array, you often just want the values themselves and don’t care about the index number (0, 1, 2, etc.).
JavaScript provides the for...of syntax to cleanly loop over sequences without needing to manually manage counter variables.
Traditional vs Modern
Instead of typing out a traditional C-style for loop:
const woods = ["oak", "pine", "maple"];
for (let i = 0; i < woods.length; i++) {
console.log(woods[i]);
}
You can write this much cleaner for...of loop:
const woods = ["oak", "pine", "maple"];
// 'wood' becomes the actual string value in each iteration
for (const wood of woods) {
console.log(wood);
}
Warning: Do not confuse for...of (which loops over the values of an array) with for...in (which loops over the string keys of an object).
Practical Example
A classic use case is filtering an array of strings to remove invalid or unwanted entries.
function getCleanMessages(messages, badWord) {
const cleanMessages = [];
for (const msg of messages) {
// Make the check case-insensitive
const lowerMsg = msg.toLowerCase();
if (!lowerMsg.includes(badWord)) {
cleanMessages.push(msg);
}
}
return cleanMessages;
}