Skip to content

Instantly share code, notes, and snippets.

@anil-pace
Created March 11, 2021 08:38
Show Gist options
  • Select an option

  • Save anil-pace/a452610a614e3391ce4e923cd96616e1 to your computer and use it in GitHub Desktop.

Select an option

Save anil-pace/a452610a614e3391ce4e923cd96616e1 to your computer and use it in GitHub Desktop.
// non-functional approach
const nums = [1, 2, 3]
let total = 0
for (let i = 0; i < nums.length; i++) {
total += nums[i]
}
console.log(total) // => 6
// functional recursive approach
function addRecursively(nums) {
return !nums.length ? 0 : nums[0] + addRecursively(nums.slice(1))
}
console.log(addRecursively(nums)) // => 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment