0

This is a snippet of JavaScript. The reduce function is being called to count a number of occurrences, and return the count to the variable total. The reduce function call can be generalized as reduce(array, someFunction, start){function body}.

The specific instance of reduce being used below is of the form reduce(array, (a,b) => a + b, 0). In the snippet below, how is the expression {count} being used, and why is it wrapped in curly {} brackets?. It seems to me it is neither a function body nor an object.

let total = scripts.reduce((n, {count}) => n + count, 0);

if (total == 0) return "No scripts found";
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
jayfox
  • 39
  • 1
  • 11
  • It’s [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and `{count}` implies that the elements in the `scripts` array are objects which have a `count` property. `{count}` extracts those. `n + count` and the initial value `0` also imply that the value of each `count` property is a number. – Sebastian Simon Jul 15 '18 at 17:13
  • This is an example from Eloquent Javascript. A few key points: 1. Look at the definition of the function countBy, on the same page. It returns an array of objects with name and count properties (counts.push({name, count: 1})) The scripts object at use here is created by this function. 2. When you use the array method reduce() on an array of objects, you must specify which object property from the object being passed in should be used as the reducer function's currentValue. The author uses destructuring, but instead of `(n, {count}) => n + count` they could have written `(n, x)=> n + x.count`. – Andrew May 31 '20 at 13:04

1 Answers1

1

It iterates through an array of objects where these objects have count property. It extracts that property and sums those values.

Here the output is 6 when you sum 1, 2 and 3.

const scripts = [
  { count: 1, something: 'else' },
  { count: 2, foo: 'bar' },
  { count: 3, baz: '23', arr: [1, 2, 3] }
];

let total = scripts.reduce((n, {count}) => n + count, 0);

console.log(total);

It is called object destructuring, more simple example would be.

const obj = { count: 3, foo: 'bar' };

const { count } = obj; // <- extracts value from count property

console.log(count);
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54