0

Can someone explain to me how this code works, or a link to somewhere that explains this? (specifically the part: +acc + +curr; )

Code in question:

let args = process.argv;
let sum = args.reduce(function(acc, curr) {
  return +acc + +curr;
});
console.log(sum);

Original solution with for-loop that does the same thing:

let result = 0;
for (i = 0; i < process.argv.length; i++) {
  result += Number(process.argv[i])
}
console.log(result);

Is the fancy code on top a good method to know / recommended practice? Thanks.

PolarisTLX
  • 171
  • 3
  • 16
  • 1
    [javascript: plus symbol before variable](https://stackoverflow.com/questions/6682997/javascript-plus-symbol-before-variable) – Alex K. Aug 08 '17 at 16:40
  • reduce, map and filter are all ways to iterate without doing for loops, they're very powerful but difficult to understand. Did you try googling? This isn't the best formatted question, you're not quite asking what is confusing you, just asking what is reduce. That can be googled. – jdmdevdotnet Aug 08 '17 at 16:55
  • No, it's not a good practice to omit the start value. Better: `const sum = process.argv.reduce((acc, arg) => acc + Number(arg), 0);` – Bergi Aug 08 '17 at 16:57

1 Answers1

1

let args = process.argv <- That gets the arguments let sum = args.reduce(function(acc, curr) { <- that uses array reduce, which reduces it to a single value return +acc + +curr; <- this uses a unary operator to convert both into a numeric representation then adds them

console.log(sum) <- that consoles out the returned value from array.reduce which is then assigned to sum.

reduce documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

unary operator documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus

As far as best practice is concerned, I don't believe that this is extremely readable. And its not a common idiom in JS. Due to type coercion, very rarely would you need this. That being said, I don't think its bad practice.

miguelsolano
  • 489
  • 3
  • 11