Using array destructuring and recursion to make your JavaScript algorithms shine

JavaScript if far from being the best-designed language in the world. I personally often feel myself like in the mine field when coding in it. But it evolves and gets better and better. I can increasingly better express the ideas in JavaScript and I feel it becomes truly powerful and pretty pleasant language to use. Here, I want to share how today one can calculate the sum of the array of numbers. The example is contrived but this example is always used in the schools to teach programming and usually, students are taught to create an accumulator variable and then iterate and accumulate the sum in that variable. How procedural is this! Now, look at what you can do with JavaScript today:

No variables, no loops, pure simplicity. It might be not very efficient code, but very simple and functional one.

Another example. I have found a quicksort implementation in JavaScript on the web (you can skip it, it is just for illustration):

It is totally procedural and very difficult to understand. Now, here is my alternative implementation, using recursion and latest JavaScript features:

So clear, so simple and again no loops or variables. Love it. Again, performance is not great here, but I am biased towards code simplicity and optimizing only when absolutely necessary.


Leave a Reply

Your email address will not be published.