0
var fn = function even (n) {
  if (n === 0) {
     return true
  }
   else return !even(n - 1)
 }

 fn(5)//=> false

 fn(2)  //=> true

Why does this function work the way it does? When I step through it when the argument is 5 it seems to call itself until n is zero which would return true but it returns false.

6
  • try writing it out what it does step by step Commented Mar 11, 2016 at 13:24
  • It is because every recursive call reverse the value of the boolean, so if it is a multiple of 2 it will return true . Any other vase would be false Commented Mar 11, 2016 at 13:26
  • On each recursive call, the returned value is negated. Then !!!!!false is true. In short: The result is negated when ! is applied odd times Commented Mar 11, 2016 at 13:28
  • The same function can be rewritten using modulo operator as function isEven(num) { return num % 2 === 0; } Commented Mar 11, 2016 at 13:30
  • @Tushar, instead of the expensive modulo you can use bit-operations for this: var isEven = n=> (n&1)===0 or var isEven = n => !(n&1); but this is OT Commented Mar 11, 2016 at 13:39

2 Answers 2

5

Every recursion step adds a negation to the previous result:

f(0) = true
f(1) = !f(0) = !true = false
f(2) = !f(1) = !!f(0) = !!true = !false = true

and so on, for f(5) you get

f(5)
    !f(4)
        !!f(3)
            !!!f(2)
                !!!!f(1)
                    !!!!!f(0)
                    !!!!(!true)
                !!!(!false)
            !!(!true)
        !(!false)
    !true
false
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't realize that the ! would accumulate. Thanks for the great answer.
0

it's because of the !

When the function is 0 it return true.

When it's 1 it will return !even(0) -> false.

When it's 2 it will return !even(1) => !(!even(0)) => !(false)=> true.

Since boolean is either true of false, meaning two possible value and you switch them again and again it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.