The Number #1 Overlooked Javascript Array Method

reduce(function callbackFn(accumulator, element, index, array) { ... }, initialValue)
  1. First, you can think of the first block of argument as an arrow function, which typically takes as arguments index and original array, just like
forEach(function callbackFn(element, index, array) { ... }, thisArg)every(function callbackFn(element, index, array) { ... }, thisArg)filter(function callbackFn(element, index, array) { ... }, thisArg)
// direction: calculate total of the array below
const array = [1, 2, 4];
const total = array.reduce((ac, e, i, a) => {
console.log(ac, e, i, a);
return ac + e;
})
console.log(total);
// direction: calculate total of the array below
const array = [1, 2, 4];
let total = 0;
total = array.reduce((ac, e, i, a) => {
console.log(ac, e, i, a);
return ac + e;
}, total)
console.log(total);
javascript weird pattern
Array.reduce((ac, e, i, a)=>{    //do your thing.}, initialValue)
// direction: calculate total of the array below
const array = [1, 2, 4];
let theSingularResultThatYouWant = 0; //any value
theSingularResultThatYouWant = array.reduce((ac, e, i, a) => {
console.log(ac, e, i, a);
return ac + e;
}, theSingularResultThatYouWant)
console.log(theSingularResultThatYouWant);

coder, founder and explorer.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Evolution of Asynchronous Actions in JavaScript

Types May Finally be Coming to JavaScript

Premier Locksmiths in Liverpool https://t.co/tsS9otF8MQ

JavaScript Frameworks and Core Web Vitals

Setting Up Navigation for React Native App

Understanding ‘Variable Shadowing’ with JavaScript

My First, Test blog post

React Native Project with NodeJS and MongoDB- Part 2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
FRANK GO

FRANK GO

coder, founder and explorer.

More from Medium

JavaScript Core Concepts

What is try-catch in JavaScript?

Javascript Testing with Mocha: Invoking Function Behavior on Click

JavaScript “this” keyword — Basic explanation