What is the difference between these two snippets

Viewed 16

I am writing some Javascript for a coding challenge and I find myself unable to complete it on my own. The first snippet is a working block of code that I am reusing from some of my previous code. I can use that for the challenge but I am now trying to figure out the difference that is making my second block not work. The goal is to have a function that takes in an array and returns the sum of all positive values. I am aware the working one is an arrow function but as far as I know the functionality should be the same.

const arr = [1,2,3,4,5]

//First snippet, doesn't work

console.log(
  arr.reduce(function (acc, num) {
    num > 0 ? acc + num : acc;
  }, 0)
);

//Second snippet, works

console.log(arr.reduce((acc, num) => (num > 0 ? acc + num : acc), 0));

0 Answers
Related