How to write more clear `for` loops in JavaScript and why it's important?
Tags: javascript, tutorial, beginners, functional
Published: 2020-01-16 20:54:50

## 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:

1. Filter array (by some value);
2. Get a new modified array;
3. Check, if each element of the array matches the condition;
4. Perform some action with element;
5. Check, if an element is contained in an array;
6. Find the value of accumulating the values of the array elements;
7. 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:

1. Takes one or more functions as arguments (i.e. _procedural parameters_);
2. Returns a function as its result;

Simple example:

```js
const twice = (f, v) => f(f(v));
const add3 = v => v + 3;

twice(add3, 7); // 13
```

See more about _higher-order functions_ on [Wiki](https://en.wikipedia.org/wiki/Higher-order_function) page.

![higher-order functions](https://thepracticaldev.s3.amazonaws.com/i/6gkyzs1mqk1lnbv6dpbo.jpg)

## 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:

```js
// 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:

```js
// 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:

```js
// 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:

```js
// 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 make` break`, `continue` or` return` during the iterative process. But if necessary, such cases usually come down to the use of the `every` or` some` methods.

### every()

Classic `for` code:

```js
// 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:

```js
// 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:

```js
// 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:

```js
// 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:

```js
// 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:

```js
// 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:

```js
// 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:

```js
// 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

<a name=""></a>
## P.S.

If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻

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 projects that need your help (and stars) 👇

- 🔥 [gowebly][gowebly_url]: A next-generation CLI tool for easily build amazing web applications with Go on the backend, using htmx & hyperscript and the most popular atomic/utility-first CSS frameworks on the frontend.
- ✨ [create-go-app][cgapp_url]: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
- 🏃 [yatr][yatr_url]: Yet Another Task Runner allows you to organize and automate your routine operations that you normally do in Makefile (or else) for each project.
- 📚 [gosl][gosl_url]: The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.
- 🏄‍♂️ [csv2api][csv2api_url]: The parser reads the CSV file with the raw data, filters the records, identifies fields to be changed, and sends a request to update the data to the specified endpoint of your REST API.
- 🚴 [json2csv][json2csv_url]: The parser can read given folder with JSON files, filtering and qualifying input data with intent & stop words dictionaries and save results to CSV files by given chunk size.

<!-- Footer links -->

[gowebly_url]: https://github.com/gowebly
[cgapp_url]: https://github.com/create-go-app
[yatr_url]: https://github.com/koddr/yatr
[gosl_url]: https://github.com/koddr/gosl
[csv2api_url]: https://github.com/koddr/csv2api
[json2csv_url]: https://github.com/koddr/json2csv