haskellcamargo / js-real-world-functional-programming

Tips and guidelines for real world functional code-bases in JS
MIT License
356 stars 14 forks source link

Question about "Return Everything"? #5

Closed XiaofengXie16 closed 6 years ago

XiaofengXie16 commented 6 years ago

In the Return everything section, you put an example of calculating factorial

const fact = n => n === 0
    ? 1
    : n * fact(n - 1)

console.log('Fact of 5: ', fact(5))

With this approach, we will potentially get a stack overflow error , if the number gets large because of recursion and I would love to know what's your thought on this. Other than that, I learned a lot from your repo and thank you for putting these things together.

cuchi commented 6 years ago

In natively functional and some other languages, recursive calls are automatically optimized by the compiler, so we don't need to worry about the stack size. In order to be optimized, your recursion call should follow some rules to match the compiler criteria, like a tail-call, for example.

JavaScript does not support it in all platforms yet, maybe that's because the language a big dynamic mess.

XiaofengXie16 commented 6 years ago

@cuchi Thanks for the explanation.