DEV Community

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

carlyraejepsenstan profile image
CarlyRaeJepsenStan • Edited on

I liked the walruses analogy! Gave me a good laugh.
If you don't mind my noob question, how would one iterate over an array/collection/vector, to create 100% immutable code? The usual loops would not be an option, as the iterator or counter variable needs to change.

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)
  const nextIterator = iterator + 1;

Enter fullscreen mode Exit fullscreen mode
carlyraejepsenstan profile image

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

dglsparsons profile image
Douglas Parsons Author

Hey, I'm glad you enjoyed the article <3.

That's a great question and thanks for asking. You're absolutely right about the iterator or counter variables changing. It's not something you can avoid really as it's so inherent to how loops work.

I don't have particular problem with that though (although in some languages you have to be careful, especially if writing asynchronous code that uses those variables). What's more important, in my opinion, is what you are doing in the iteration - are you mutating an array in place, or returning a new array? Using map and reduce where possible helps a lot.

Hope that helps!

carlyraejepsenstan profile image

I see - that question has bugged me a lot while I'm coding. Thanks for the advice!