DEV Community

Discussion on: How to write IMMUTABLE code and never get stuck debugging again

Collapse
bytebodger profile image
Adam Nathaniel Davis

The answer is: recursion. In true Functional Programming (which heavily features immutability), there are no loops. People throw around terms like "functional programming" and "immutability", but they rarely think about what it takes to fully implement these features.

Everything that you can do with a loop, you can also do with a recursive function. Here's a simple example:

const countToTen = (iterator = 1) => {
  if (iterator > 10)
    return;
  console.log(iterator);
  const nextIterator = iterator + 1;
  countToTen(nextIterator);
}

countToTen();
Enter fullscreen mode Exit fullscreen mode
Collapse
carlyraejepsenstan profile image
CarlyRaeJepsenStan

Wow, thanks so much! This is exactly what I was looking for.