Recursive Functions

Yeeeeeun_IT·2022년 8월 26일
0

Recursive Functions (재귀함수)

함수가 자기 자신을 호출하는 것을 재귀 호출이라하며, 자기 자신을 호출하는 함수는 재귀함수이다.

재귀함수는 반복되는 처리를 위해 사용한다

반복문으로 10부터 0까지 출력하기

function countdown(n){
  for (let i=n; i>=0; i--)
    console.log(i)
}
countdown(10)

재귀함수로 10부터 0까지 출력하기

function countdown(n){
  for (n < 0) return; 
    console.log(n)
  countdown(n-1); // 재귀 호출
}
countdown(10)```

이처럼 자기 자신을 호출하는 재귀함수를 사용하면 반복되는 처리를 반복문 없이 구현할 수 있다.

예시 : 팩토리얼(1부터 자기자신까지의 모든 양의 정수의 곱) 구하기

출처: 모던 자바스크립트 Deep Dive

profile
🍎 The journey is the reward.

0개의 댓글