Thinking Beyond For & Nested loop :- Part 1

Vikash Agarwal
Frontend Weekly
Published in
2 min readJun 30, 2020
Image from: — https://unsplash.com/photos/KQ0C6

As we write lot of complex javascript code, heavily using Array, one thing I see missing from most of the developers to think beyond traditional for/.forEach loop.

In the rush to achieve a task, developers often write unoptimized code or simply copy and paste from online websites.

Developers are so used to write old style for loop, that they don’t think beyond it and don’t try to optimize it.

Let’s explore with an example :- Filtering an array.

Example 1:- Function to filter even numbersfunction filterEvenNumber(array){
const resultingArray = [];
array.forEach(number => {
if (number % 2 === 0){
resultingArray.push(number)
}
})
return resultingArray;
}

Problem with above logic

  • Extra Code:- Contains unnecessary logic & it’s lot more code.
  • Lack of Knowledge:- Clearly indicates developer’s lack of knowledge & interest of javascript.
  • Code Review:- Creates headache for the serious code reviewer.

Even though there are several useful functions available right out of the box in the Array interface, it’s really sad to see developers just moved to using .forEach for all sorts of task.

Example 1:- Function to filter even numbers :- simplified versionfunction filterEvenNumber(array){
array.filter(number => number % 2 === 0);
}

Above code has many benefits

  • Less Code:- As you can see, it’s having lesser code. Imagine in the large code base, how much space it will save.
  • Easy to understand:- Clearly indicates developers thought and knowledge of using right function for the right task.
  • Code Review:- Saves lot of time during code review.

Lets take an another example :- Joining array elements

Example #2 :- create string of object separated by comma (,)const array = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'}
];
function toString(array){
let result = '';
array.forEach((obj, index) => {
if (index === 0){
result = obj.name;
} else {
result = result + ',' + obj.name;
}
})
return result;
}

Let’s reduce above 11 lines to 3 lines of code and make above clean to write, read and maintain.

Example #2 :- create string of object separated by comma (,) - Simplified Versionconst array = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'}
];
function toString(array){
return array.map(obj => obj.name).join(',')
}

Knowing and using map & join makes code a lot easier to understand.

Explore Array interface to learn all the functions it has to offer which will make you a lot better developer.

Related story below

--

--