Sumit kumar Singh
1 min readMay 5, 2023

--

Thank you for your compliment! Regarding your statement, I would say that it's not entirely accurate.

The difference between forEach and map is not primarily related to time or space complexity, but rather to their intended purpose and the return value they provide.

forEach is used for iterating over an array and performing a side effect on each element, such as printing it to the console or modifying it in place. It doesn't return a new array, and its time complexity is O(n) since it visits each element once.

map, on the other hand, is used for transforming an array into a new array by applying a function to each element. It returns a new array with the same length as the original array, where each element has been transformed according to the function. Its time complexity is also O(n) since it visits each element once, but it requires additional space to store the new array.

Therefore, if you need to modify an array in place, forEach is a good choice. But if you need to create a new array with transformed elements, map is the way to go. The choice between them is not related to time or space complexity, but rather to the desired behavior and outcome.

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Topmate: https://topmate.io/sumit_kr_singh 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks

No responses yet