Am a beginner confused about reduce

Let arr = [0,1,2,3,4,5];

Let answer = arr.reduce((acc,curr) => {
        If(curr == 2){
            return "fresh";
        }else{
            return acc
        }
})

console.log(answer)

If that else statement returning acc(which i didn’t set to anything) isn’t their it returns undefined…Why does it need that to work

Because every function in JavaScript by default returns undefined (nothing to do with reduce).
And if you don’t provide default value for acc in reduce, then for the first loop its value is the first element of the array and curr is the second.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

I just simplified this…I used this for a much larger approach run the code…My question why isn’t it returning fresh…unless I return acc…

I was able to get it to return “fresh” when I uncapitalized the if and let keywords.

Those should be lowercase.

Screen Shot 2021-03-13 at 11.10.56 PM

Did you remove the return acc in the else?

I just posted the screenshot.

Was that what you were looking for?

if (curr = 2) will always be true, so every iteration will return "fresh" and else will never be called :slight_smile:
But I guess it’s a typo just like Let and If.

2 Likes

This is crazy but I ran the exact thing you typed and got undefined

Okay nope your using…Assignment I used equality

What is your current code?

I just edited it sorry

Because acc value is the one you return from the callback function. And if you don’t have else it’ll be undefined.

Editing the first post makes it really hard to follow the conversation.

Anywho, it looks like you still have a typo where you have capitalized If

Am sorry don’t mind the capitalization

You can’t ignore the capitalization though. It has meaning

Okay now check (curr == 5) it returns fresh even without return acc

Because it’s the last item, no undefined to overwrite it.

let arr = [0,1,2,3,4,5];

let answer = arr.reduce((acc,curr) => {
  if (curr == 2) {
    return "fresh";
  } else {
     return acc;
  }
})

console.log(answer);

is equivalent to

let arr = [0,1,2,3,4,5];

let acc = arr[0];
for (let i = 1; i < arr.len; i++) {
  if (curr == 2) {
    acc = "fresh";
  } else {
    acc = acc;
  }
}
let answer = acc;

console.log(answer);
1 Like

Thank You very much this is what has been confusing me all along…I never knew just returning “fresh” set acc to “fresh”