avatarMohamed Amine HAINE

Summary

The webpage discusses the benefits of using JavaScript array methods over the traditional forEach loop for more maintainable and scalable code.

Abstract

The article titled "Stop Using ForEach and Use This Instead" advocates for the use of JavaScript's built-in array methods as a superior alternative to the conventional forEach loop. It argues that these methods, such as filter, map, reduce, every, and some, not only make the code more concise but also enhance readability and maintainability. The author illustrates this by comparing examples of common array operations, such as finding odd numbers, doubling elements, summing array values, and checking element conditions, using both forEach and the recommended array methods. The article emphasizes the distinction between imperative programming, which focuses on the process of how things are done, and declarative programming, which emphasizes the outcome of what needs to be done. By refactoring the code to use these array methods and defining reusable utility functions, the author demonstrates how the code becomes more declarative, easier to understand, and closer to natural language, potentially even accessible to non-developers.

Opinions

  • The author believes that good coders should write code that is not only functional but also maintainable and scalable.
  • The preference for declarative programming over imperative programming is clear, with the former being praised for producing shorter and more readable code.
  • The author suggests that using JavaScript's array methods can significantly improve code quality by making it more declarative.
  • Reusable utility functions are encouraged to further enhance code clarity and reduce redundancy.
  • The article implies that the shift towards using array methods could lead to a broader improvement in coding practices within the developer community.
  • The author values the importance of following up with similar coding practices, as indicated by the invitation to read another article on improving code cleanliness.
  • The article concludes with a call to action for readers to engage with the content by clapping, following, and exploring additional resources provided by the Plain English community.

Stop Using ForEach and Use This Instead

Photo by Thomas Bormans on Unsplash

As coders, our job is to write a code that works. It’s fine, but it’s not enough.

As good coders, our job is to write a code that works, maintainable and scalable.

What about array handling ?

A lot of programming languages use forEach to iterate around an array that allow us to do some calculations.

JavaScript / TypeScript provides several useful functions that save you from having to use forEach.

Let’s see how.

Using Foreach

Let’s assume we have a number array, and we want to :

  • Get the odd numbers.
  • Get the doubled numbers.
  • Get the sum of all his elements.
  • Check if all numbers are lower than 5.
  • Check if at least one number is lower than 5.
const numbers = [1, 2, 3, 4, 5, 6];

/** Get Odd Numbers */
const oddNumbers: number[] = [];
numbers.forEach((number) => {
  if (number % 2 !== 0) {
    oddNumbers.push(number);
  }
});
console.log(oddNumbers); // Output : [1, 3, 5]

/** Get Doubled numbers */
const doubledNumbers: number[] = [];
numbers.forEach((number) => {
  doubledNumbers.push(number * 2);
});
console.log(doubledNumbers); // Output : [2, 4, 6, 8, 10, 12]

/** Get Sum Numbers */
let sum: number = 0;
numbers.forEach((number) => {
  sum += number;
});
console.log(sum); // Output : 21

/** Check Is All Numbers Lower Than 5 */
let isAllNumbersLowerThan5 = true;
numbers.forEach((number) => {
  if (number >= 5) {
    isAllNumbersLowerThan5 = false;
  }
});
console.log(isAllNumbersLowerThan5); // Output : false

/** Check Is At Least One Number Lower Than 5 */
let isAtLeastOneNumberUnder5 = false;
numbers.forEach((number) => {
  if (number < 5) {
    isAtLeastOneNumberUnder5 = true;
  }
});
console.log(isAtLeastOneNumberUnder5); // Output : true

Using JavaScript Array Methods

Let’s assume we have the same needs as before.

const numbers = [1, 2, 3, 4, 5, 6];

/** Get Odd Numbers */
const oddNumbers = numbers.filter((number) => number % 2 !== 0);
console.log(oddNumbers); // Output : [1, 3, 5]

/** Get Doubled numbers */
const doubledNumbers = numbers.map((number) => number * 2);
console.log(doubledNumbers); // Output : [2, 4, 6, 8, 10, 12]

/** Get Sum Numbers */
const sum = numbers.reduce((sumAcc, number) => sumAcc + number, 0);
console.log(sum); // Output : 21

/** Check Is All Numbers Lower Than 5 */
const isAllNumbersLowerThan5 = numbers.every((number) => number < 5);
console.log(isAllNumbersLowerThan5); // Output : false

/** Check Is At Least One Number Lower Than 5 */
const isAtLeastOneNumberUnder5 = numbers.some((number) => number < 5);
console.log(isAtLeastOneNumberUnder5); // Output : true

There is a big difference in code size between the two ways.

The first code is called imperative programming. The second one is called declarative programming.

The difference is, imperative programming focuses on how the code does the things, unlike declarative programming focuses on what the things the code should do.

The above code is declarative, but it can be made more so.

Let’s do it.

const numbers = [1, 2, 3, 4, 5, 6];

/** Get Odd Numbers */
const oddNumbers = numbers.filter(checkIsOddNumber);
console.log(oddNumbers); // Output : [1, 3, 5]

/** Get Doubled numbers */
const doubledNumbers = numbers.map(doubleNumber);
console.log(doubledNumbers); // Output : [2, 4, 6, 8, 10, 12]

/** Get Sum Numbers */
const sum = numbers.reduce(addTwoNumber, 0);
console.log(sum); // Output : 21

/** Check Is All Numbers Lower Than 5 */
const isAllNumbersLowerThan5 = numbers.every(checkIsNumberLowerThan5);
console.log(isAllNumbersLowerThan5); // Output : false

/** Check Is At Least One Number Lower Than 5 */
const isAtLeastOneNumberUnder5 = numbers.some(checkIsNumberLowerThan5);
console.log(isAtLeastOneNumberUnder5); // Output : true

Let’s write the math util functions

/** math utils */
const checkIsOddNumber = (number: number) => number % 2 !== 0;
const doubleNumber = (number: number) => number * 2;
const addTwoNumber = (number1: number, number2: number) => number1 + number2;
const checkIsNumberLowerThan5 = (number: number) => number < 5;

Here, we just wrote the math util functions that allow us to avoid writing anonymous functions inside the array methods.

Now, our code is more declarative, even a non-developer can understand it, I exaggerate a bit (or not).

Conclusion

The big advantage of declarative programming is that procure to us a code shorter and easier to read than imperative programming.

What do you think about this way of programming ?

Resources

You will probably never see my articles again, unless you follow for more.

If you are interested in making the code cleaner, feel free to check my Stop Using Try Catch and Use this Instead.

In Plain English

Thank you for being a part of our community! Before you go:

Programming
JavaScript
Typescript
Software Development
Software Engineering
Recommended from ReadMedium