JavaScript Control Flow Loops
Loops are nothing new to us, as we've already looked at loops the functional way when we transformed, filtered, searched through and sorted arrays. But how do we execute the same code block thousands of times, an infinite amount of times or a fixed amount of times? That's where imperative loops have their main advantage; performance and flexibility.
We already issued this warning when we introduced conditionals, but the same is true for loops: use the knowledge you learned in the previous lessons to solve problems and fall back to imperative loops only when the functional style performs considerably worse or is a bad fit for the problem you're solving.
That being said, imperative loops can do anything functional style loops can, but that doesn't hold true the other way around.
Example where functional code is better
Problems involving iterable types like arrays are often better fitted
for functional style solutions. Functional solutions tend to be
shorter and easier to read. Each imperative loop is unique and
requires us to read every line carefully to understand its
goal. map, filter, reduce, find and the other functional style
methods do one thing and one thing only.
Imperative transformation of an array can be written as
const nums = [1, 2, 3]const numsPlusOne = []for (let i = 0; i < nums.length; i++) {numsPlusOne.push(nums[i] + 1)}console.log(nums) // [1, 2, 3]console.log(numsPlusOne) // [2, 3, 4]
but is much better solved using map as shown below, while at the
same time being easier for us humans to understand.
const nums = [1, 2, 3]const numsPlusOne = nums.map(x => x + 1)console.log(nums) // [1, 2, 3]console.log(numsPlusOne) // [2, 3, 4]
Example where imperative code is better
We want to sum all the numbers between 1 and 100 with a step of 3, which means we're adding up the numbers 1, 4, 7, etc. up to 100. This is not straight forward to solve using functional style loops, but extremely easy for imperative loops.
let sum = 0;for (let x = 1; x < 100; x += 3) {sum += x}console.log(sum) // 1617
A functional JavaScript solution would be so messy, that we're not even going to try.
Read more on MDN
Looping code