Stop Using ForEach and Use This Instead
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
- All JavaScript array methods that you can use : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
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:
- Be sure to clap and follow the writer! 👏
- You can find even more content at PlainEnglish.io 🚀
- Sign up for our free weekly newsletter. 🗞️
- Follow us: Twitter(X), LinkedIn, YouTube, Discord.
- Check out our other platforms: Stackademic, CoFeed, Venture.