함수가 자신을 호출하면 재귀라고 하며 JavaScript에서도 동일하게 작동합니다. 함수가 자신을 호출하는 예를 살펴보겠습니다.
예시
라이브 데모
<html>
<body>
<script>
function displayFact(value) {
if (value < 0) {
return -1;
}
// 0 factorial is equal to 1
else if (value == 0) {
return 1;
} else {
return (value * displayFact(value - 1));
}
}
var res = displayFact(5);
document.write("5 factorial = "+res);
</script>
</body>
</html>