DEV Community

loading...
Cover image for How to write more clear `for` loops in JavaScript and why it's important?

How to write more clear `for` loops in JavaScript and why it's important?

koddr profile image Vic Shóstak Updated on ・3 min read

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:

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

twice(add3, 7); // 13
Enter fullscreen mode Exit fullscreen mode

See more about higher-order functions on Wiki page.

higher-order functions

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 ]
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

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" ]
Enter fullscreen mode Exit fullscreen mode

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" ]
Enter fullscreen mode Exit fullscreen mode

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 the every 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");
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 — write a comment below & follow me. Thx! 😘

Discussion (2)

Collapse
surjithctly profile image
Surjith S M

In your filter() example,

let odd = numbers.filter(num => num % 2);

shouldn't be?

let odd = array.filter(num => num % 2);
Collapse
koddr profile image
Vic Shóstak Author

Thanks for issue! Fixed 😉

Forem Open with the Forem app