Tuesday, November 5, 2013

Native vs Functional Loops

Native loops...

...are a functional portion of the javascript language and allow you to repeat functionality of code for a certain number of times specified by the conditions of the loop.

These examples are fairly easy and trivial. If you are not proficient in javascript loops, I highly recommend learning how to construct one from scratch here.

Functional loops provide a different mechanism for looping over the items in an array. They also have much larger implications for memory management and coding techniques.

Example: a user wants to loop over items in an array and perform a static operation.

This example is obviously bad, because the same result could be achieved by calling target = array.slice();, but look a little bit closer at the example below.

Boom. Now you can enclose objects with functions and local variables.

So now that we have our toolset, let's make a few rules on when certain loops are needed.

Native loops

  • When a functional context is not needed
  • Concatenating strings
  • Looping through strings
  • Anywhere that performance matters greatly

To put it simply, if the code requires speed and performance, chances are a for loop may be indicated. Especially for simple operations.

Lastly, the indications for functional loops...

Functional loops

  • When a closure is needed(I.E. Variables need to be obscured)
  • Chaining Maps (see example below)
  • When the calling function needs to be called multiple times in other places in the code (using a named function)
  • When Performance probably doesn't matter (and trust me, javascript is pretty fast)
  • When file size DOES matter

The code looks more fun, and is more expressive. It's less terse, but that's the price you pay for a functional language expression

In functional health

-Josh

No comments:

Post a Comment