This is a read-only archive of the Framer Community on Facebook.

What is Framer? Join the Community
Return to index
George Otsubo
Posted Oct 27 - Read on Facebook

Hello, wondering if somebody can help me understand for() vs .map() loops better. Trying to pick apart and learn from an old Ed Chao prototype and I was curious to see if a for() loop worked instead of .map() but it errors out. I guess .map() creates it's own scope but...why and how? When should you use a .map() vs a for() loop?


Niels van Hoorn

For and map are indeed two tools to do a similar thing, but they work a bit different. As you mentioned, for is a control flow statement that doesn't change the scope. for just loops over the variables you provide.
Map is a javascript function on Array:

You provide map with a function that it calls for every element in the array and it creates a new array with the returned values from that function. Because this uses a function, it automatically creates a new scope.

Typically a for loop is used when you want to perform an action for every value in an array, while map() is used if you want to transform an array of values into an array of other values.

Now back tho the Card-Stack example. If a for-loop would be used instead of map(), "i" would be assigned to the next value in the array for every iteration of the loop. This means that when the loop is done, the variable "i" would point to the last value in the array (0 in this case).

Inside of the loop that variable is used in the callback functions of event handlers and Utils.delay. These functions are called after the for-loop is done. So without capturing the variable "i" in a scope, its value would be 0 in all callback functions. This is why map is used in this case to capture the value of "i" inside of a function for every iteration.

I hopes this makes it a bit more clear. If you want to read up on scope, there's a section about it in our programming guide:

Ed Chao

Niels has explained this far better than I could :). Using a for loop didn't allow me to assign unique index values to each card. Map did.

Read the entire post on Facebook