Recursion in JavaScript

June 23, 2019

call stack

  • Any time a function is invoked it's placed(pushed) on the top of the call stack.

  • When seeing the return keyword or when the function ends, the compiler will remove(pop)

When we write recursive functions, we keep pushing new functions onto the call stack!

How recursive functions work

Invoke the same function with a different input until you reach your base case.

base case: The condition when the recursion ends.

SO, 2 essential parts of a recursive function:

  1. Base Case
  2. Different Input

Basic recursive function

const sumRange = num => {
  if (num === 1) {
    return 1
  }

  return num + sumRange(num - 1)
}

console.log('--------')
console.log(sumRange(10))
console.log(sumRange(5))
console.log('--------')

Profile picture

Written by YU-HSIN, CHEN,
Front-end Engineer at PayPay Corporation.,
Loves pursuing modern web development.Find me on LinkedIn