-2

Just following mdn tutorial on reduce on javascript, Can someone please explain to me why below I cannot use the curly brackets around the callback?

const array1 = [1, 2, 3, 4];
    
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
    
// expected output: 10
const sumWithInitialTest = array1.reduce( (pv, cv) => 
  { pv + cv }
)
    
console.log(sumWithInitialTest)

Obviously, without curly bracket, it works fine

const array1 = [1, 2, 3, 4];
    
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
    
// expected output: 10
const sumWithInitialTest = array1.reduce( (pv, cv) => 
   pv + cv 
)
    
console.log(sumWithInitialTest)
D M
  • 5,769
  • 4
  • 12
  • 27

1 Answers1

1

Add return if you want to use curly bracket

const array1 = [1, 2, 3, 4];
    
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
    
// expected output: 10
const sumWithInitialTest = array1.reduce( (pv, cv) => 
    { return pv + cv }
)
    
console.log(sumWithInitialTest)
Evren
  • 4,147
  • 1
  • 9
  • 16