Coding Tip: Try to Code Without Loops
You might uncover better solutions
Update: This article is now part of my book “Learn Coding with Modern JavaScript”.
Read the updated version of it at jscomplete.com/beginning-js.
In a previous article, I wrote about how trying to solve coding challenges without using if-statements might help uncover better solutions. In this article, we will explore how to solve some more challenges, but this time without using any loops.
By loops, I mean imperative loops like for
, for...in
, for...of
, while
, and do...while
. All of these are similar in the way that they provide an imperative way to perform iterations. The alternative is to perform iterations in a declarative way.
Imperative vs Declarative
This is a big topic. The simplest thing we can say about it is that:
- Imperative represents the HOW
- Declarative represents the WHAT
What? How? And why should you care?
An imperative approach represents a list of steps. Do this first, then do that, and after that do something else. For example: Go over a list of numbers one by one and for every one add its value to a running sum.