Always defaulting to iterative thinking

Does anyone have this problem? I always find my first port of call is to think to solve things too much with iteration and can never seem to think of the more concise methods. I never seem to be able to remember the more concise provided functions to help me. I always end up making a long over-done iterative solution with like 10 million (exaggerated) variables to keep track of if statement results.

I mean if you have to loop, you have to loop.

But you should use all the nice built-in methods as much as possible and avoid for loops with custom logic already provided by the built-in methods (like includes, find, findIndex, filter, and so on).

  • If you need to transform elements use map.

  • If you need to filter down the elements use filter.

  • If you need to change the shape of the data use reduce (but don’t go too crazy with it).

  • If you just need to loop prefer forEach when possible. Or use for...of.

You can have the MDN array page handy and look at the methods when needed.

Hey thanks very much :slight_smile:

One other thing to do is to practice using the special functions by giving yourself some exercises and then only using one of these functions for all of the exercises until you really really know it well.

Eg for map

Function to take a sentence and insert the word “like” in between each word. Eg I like cats. I like like like cats.

Function to take an array of perfect squares and square root each of them and give a new function [4, 9, 16] gives [2,3,4]

Cool idea thank you, I thumbed it up :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.