Coding, Insights, and Digital Discoveries πŸ‘©πŸ»β€πŸ’»

From Stay-at-Home Mom to a Developer After 50

Published on

JavaScript Loops: When to Use Map, forEach, for, and for...of

loop in javascript

Recently, I started working on a simple To-Do List app using Vanilla JavaScript to refresh my core JS knowledge. One specific challenge I faced was choosing the best loop to update a task’s completed status in localStorage.

Since I often work with React.js and Next.js, I’m used to using .map() everywhere because of its immutability and how it works well with state updates. But working on this project reminded me that .map() isn’t always the best tool for every situation.

πŸ” The Problem: Updating a Task's Completion Status Efficiently

In my app, each task is stored as an object in an array inside localStorage. When a user checks off a task, I needed to find that task in the array, update its completed status, and save the updated list back to storage.

My Final Function

function updateTaskStatus(taskText, checked) {
    if (checked) {
        let tasks = getTasksFromStorage();    

        for (let task of tasks) {
            if (task.text === taskText) {
                task.completed = true;
                break;
            }
        }
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
}

πŸ”„ Why I Chose for...of

At first, I considered .map(), since I use it frequently in React:

tasks = tasks.map(task => 
    task.text === taskText ? { ...task, completed: checked } : task
);

But then I realized:

  • .map() creates a new array, even though I only needed to modify one item.
  • Performance-wise, .map() is unnecessary here, because it loops through every task even after I find the right one.
  • Since I wasn’t re-rendering a UI like in React, mutating the object (task) directly was fine.

That’s why I switched to for...of. It allowed me to:

  • βœ… Directly modify the task in the array (since objects are referenced, not copied).
  • βœ… Use break to exit early, improving efficiency.
  • βœ… Keep the code readable and easy to understand (when compared with for loop using index).

πŸ“Š A Quick Guide: When to Use Each Loop

During this exercise, I revisited all the common looping methods and their best use cases:

Loop TypeBest ForCan Stop Early?Modifies Original Array?Readability
.map()Transforming all elements into a new array❌ No❌ No (returns a new array)βœ… Clear but overkill for updates
.forEach()Running a function on each element❌ Noβœ… Yesβœ… Readable but inefficient for updates
for loopFull control over iteration (especially with indexes)βœ… Yesβœ… YesπŸ”Ά A bit more verbose
while loopWhen loop conditions may change dynamicallyβœ… Yesβœ… YesπŸ”Ά Less readable
for...inLooping over object properties (not arrays)❌ Noβœ… Yes❌ Not recommended for arrays
for...ofBest for iterating over arrays when mutating elementsβœ… Yesβœ… Yesβœ… Best balance of efficiency & readability

βš›οΈ What About React?

React developers (including myself) tend to default to .map() for everything, but this project made me rethink that habit.

  • In React, .map() makes sense because we usually return new JSX elements, and React re-renders efficiently.
  • But for data updates like this, where you’re working with an array of objects without triggering re-renders, mutating an object directly using for...of is the better choice.

πŸ”„ A Refreshing Revisit to JavaScript

Working on this simple Vanilla JavaScript To-Do List app after spending so much time with React and Next.js was a great reminder of how refreshing it is to dive back into the core concepts of JS. It felt like dusting off some old tools in the toolbox that I'd almost forgotten about! πŸ€“

Sometimes, after working with React for a while, you can get so used to certain patterns that you forget there are other, more direct ways of solving problems in Vanilla JS. Taking a step back and re-engaging with JavaScript on its own helped me reinforce those fundamental concepts, and I really enjoyed it. It’s always nice to feel like I’m getting back to the basics and understanding them better.

← See All Posts