简体   繁体   中英

Why does this recursive javascript function return what it does?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM