Introduction
What are we saying to yet another article with the best JavaScript experience? Of cause, "why not, give two please"! And adding it to browser's bookmarks... 😉
But jokes aside. Today, I would like to talk about a serious topic.
As if there are "not serious" topics in modern JavaScript, yeah.
Why do we use for
loops in our code?
Yes, I know "we iterate over all elements of the array and do something", but what exactly? Here is my list:
- Filter array (by some value);
- Get a new modified array;
- Check, if each element of the array matches the condition;
- Perform some action with element;
- Check, if an element is contained in an array;
- Find the value of accumulating the values of the array elements;
- And many more...
Too huge list for one small for
function, don't you think so? But "what else can we use?", you will ask me and my answer is...
Higher-order functions!
Using higher-order functions makes your JavaScript code:
- More clear & readable;
- Easier to debug;
And it's important, because your personal DX (developer experience) it's your productivity!
Hmm... What? 🤔
In mathematics and computer science, a higher-order function is a function that does at least one of the following:
- Takes one or more functions as arguments (i.e. procedural parameters);
- Returns a function as its result;
Simple example:
const twice = (f, v) => f(f(v)); const add3 = v => v + 3; twice(add3, 7); // 13
See more about higher-order functions on Wiki page.
Examples and compare
Let's go in the same order. We will consider an example using for
and a modern approach.
filter()
Classic for
code:
// Define arrays var array = [1, 2, 3, 4, 5]; var new_array = []; // Odd function function Odd(num) { return num % 2; } // For loop for (var i = 0, total = array.length; i < total; i++) { var num = array[i]; if (Odd(num)) new_array.push(num); } // Result: [ 1, 3, 5 ]
Similar, with filter()
function:
// Define array let array = [1, 2, 3, 4, 5]; // Odd function let odd = array.filter(num => num % 2); // Result: [ 1, 3, 5 ]
map()
Classic for
code:
// Define arrays var array = ["John", "Alisa", "Bill", "Jane"]; var new_array = []; // For loop for (var i = 0, total = array.length; i < total; i++) { new_array[i] = array[i].toUpperCase(); } // Result: [ "JOHN", "ALISA", "BILL", "JANE" ]
Similar, with map()
function:
// Define array let array = ["John", "Alisa", "Bill", "Jane"]; // upperCase function let upperCase = array.map(name => name.toUpperCase()); // Result: [ "JOHN", "ALISA", "BILL", "JANE" ]
Please note: if you use
map
, then you cannot makebreak
,continue
orreturn
during the iterative process. But if necessary, such cases usually come down to the use of theevery
orsome
methods.
every()
Classic for
code:
// Define arrays var array = [1, 2, 3, 4, 5, 0]; // For loop for (var i = 0, total = array.length; i < total; i++) { if (array[i] === 0) console.log("zero present in array"); }
Similar, with every()
function:
// Define array let array = [1, 2, 3, 4, 5, 0]; // isZero function let isZero = array.every(num => num > 0); // Print result if (!isZero) console.log("zero present in array");
forEach()
Classic for
code:
// Define arrays var array = ["DEV", "Community", "dev.to"]; // Print function function Print(word) { console.log(word); } // For loop for (var i = 0, total = array.length; i < total; i++) { Print(array[i]); } // Result: DEV Community dev.to
Similar, with forEach()
function:
// Define array let array = ["DEV", "Community", "dev.to"]; // Print words array.forEach(word => console.log(word)); // Result: DEV Community dev.to
some()
Classic for
code:
// Define arrays var array = ["we", "love", "dev.to"]; for (var i = 0, total = array.length; i < total; i++) { if (array[i] === "love") { console.log("found love"); return; } }
Similar, with some()
function:
// Define array let array = ["we", "love", "dev.to"]; // isLove function let isLove = array.some(word => word === "love"); // Print result if (isLove) console.log("found love");
reduce()
Classic for
code:
// Define arrays var array = [1, 2, 3, 4, 5]; // Initial result var result = 0; // For loop for (var i = 0, total = array.length; i < total; i++) { result = result + array[i]; } // Result: 15
Similar, with reduce()
function:
// Define array let array = [1, 2, 3, 4, 5]; // Print result let result = numbers.reduce((acc, val) => acc + val, 0); // Result: 15
Hope, it helps you to write clear and readable code now!
Photo by
[Title] Marvin Meyer https://unsplash.com/photos/SYTO3xs06fU
[1] Headway https://unsplash.com/photos/5QgIuuBxKwM
P.S.
If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻
❗️ You can support me on Boosty, both on a permanent and on a one-time basis. All proceeds from this way will go to support my OSS projects and will energize me to create new products and articles for the community.
And of course, you can help me make developers' lives even better! Just connect to one of my projects as a contributor. It's easy!
My main projects that need your help (and stars) 👇
- 🔥 gowebly: A next-generation CLI tool that makes it easy to create amazing web applications with Go on the backend, using htmx, hyperscript or Alpine.js and the most popular CSS frameworks on the frontend.
- ✨ create-go-app: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
Top comments (2)
In your filter() example,
shouldn't be?
Thanks for issue! Fixed 😉