LEARNING JAVASCRIPT - Trang 221

It’s important that a recursive function has a stopping condition; without it, it will keep

recursing until the JavaScript interpreter decides the call stack is too deep (which will

cause your program to crash). In our

findNeedle

function, we have two stopping

conditions: we stop because we found the needle, or we stop because there is no hay‐

stack. Because we’re reducing the size of the haystack every time, it’s inevitable that

we will eventually reach one of these stopping conditions.
Let’s consider a more useful, time-honored example: finding the factorial of a num‐

ber. The factorial of a number is the number multiplied by every number up to it and

is denoted by an exclamation point after a number. So 4! would be 4 × 3 × 2 × 1 = 24.

Here’s how we would implement this as a recursive function:

function

fact

(

n

) {

if

(

n

===

1

)

return

1

;

return

n

*

fact

(

n

-

1

);

}

Here we have a stopping condition (

n === 1

), and every time we make the recursive

call, we reduce the number

n

by one. So eventually we’ll get to 1 (this function will fail

if you pass it

0

or a negative number, though of course we could add some error con‐

ditions to prevent that from happening).

Conclusion

If you have experience with other functional languages—like ML, Haskell, Clojure, or

F#—this chapter was probably a cakewalk for you. If not, it probably stretched your

mind a bit, and you might be reeling a little from the abstract possibility of functional

programming (believe me, when I first encountered these ideas, I certainly was). You

might be a little overwhelmed by the various ways you can accomplish the same

thing, and wondering which way is “better.” I’m afraid there’s no easy answer to that

question. Often it depends on the problem at hand: some problems strongly suggest a

certain technique. A lot also depends on you: what techniques resonate with you? If

you find the techniques presented in this chapter bewildering, I encourage you to

reread it a few times. The concepts here are extremely powerful, and the only way

you’ll know if they’re useful techniques for you is if you take some time to understand

them.

Conclusion | 197

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.