From logical view it looks fine. You could also try the ternary operator if you want to play around.
return n <= 0 ? 0 : sum(arr, n - 1) + arr[n - 1];
The first block is the if question. If its true is goes to the second block (starts whith ?) and if its false it goes to the third block (starts with :).
Answer from Athii on Stack OverflowFrom logical view it looks fine. You could also try the ternary operator if you want to play around.
return n <= 0 ? 0 : sum(arr, n - 1) + arr[n - 1];
The first block is the if question. If its true is goes to the second block (starts whith ?) and if its false it goes to the third block (starts with :).
I don't think we can make it shorter:
const sum = (arr,n) => --n<0 ? 0 : sum(arr,n) +arr[n]
console.log ( sum([1], 0) )
console.log ( sum([2, 3, 4], 1) )
console.log ( sum([2, 3, 4, 5], 3) )
.as-console-wrapper { max-height: 100% !important; top: 0; }
Replace Loops using Recursion - Explained
Basic JavaScript - Replace Loops using Recursion
Replace Loops using Recursion
freeCodeCamp Challenge Guide: Replace Loops using Recursion - Guide - The freeCodeCamp Forum
Videos
From logical view it looks fine. You could also try the ternary operator if you want to play around.
return n <= 0 ? 0 : sum(arr, n - 1) + arr[n - 1];
The first block is the if question. If its true is goes to the second block (starts whith ?) and if its false it goes to the third block (starts with :).
I don't think we can make it shorter:
const sum = (arr,n) => --n<0 ? 0 : sum(arr,n) +arr[n]
console.log ( sum([1], 0) )
console.log ( sum([2, 3, 4], 1) )
console.log ( sum([2, 3, 4, 5], 3) )
.as-console-wrapper { max-height: 100% !important; top: 0; }