简体   繁体   中英

Why does this function return true?

const res = (n => {
  const even = x => {
    if (x === 0)
      return true
    else {
      const odd = y => !even(y)
      return odd(x - 1)
    }
  }
  return even(n)
})(42)

console.log(res) //=> true

since 42 was used in the paramtersbut it says to return true only if x is 0 with strictly equaling its type and value, I'm not sure why true is returned. I thought any value but 0 should return false. Can someone please explain this to me, I am very new to javascript and programming.

If you strip all unnecessary parts with local functions and IIFE, then you get just a test for zero, then it's an even value or a recursive call of not even with a reduced value by one.

 const even = x => x === 0 || !even(x - 1); console.log(even(42)) // true console.log(even(43)) // false 

Whats happens is a recursive call of even

  n result of calling simplified -- ----------------- ---------- 8 !even(7) !even(7) 7 !!even(6) even(6) 6 !!!even(5) !even(5) 5 !!!!even(4) even(4) 4 !!!!!even(3) !even(3) 3 !!!!!!even(2) even(2) 2 !!!!!!!even(1) !even(1) 1 !!!!!!!!even(0) even(0) 0 !!!!!!!!true true 

Lets simplify.

Step 1

const f = n => {
    const even = x => {
        if (x == 0)
            return true
        else {
            const odd = y => !even(y)
            return odd(x - 1)
        }
    }

    return even(n)
}

Step 2

const f = n => {
    const even = x => {
        if (x == 0) return true
        return !even(x - 1)
    }

    return even(n)
}

Step 3

const f = n => {
    let modificator = true

    while (true) {
      if (n == 0) return modificator
      modificator = !modificator
      n = n - 1
    }
}

Step 4

const f = n => !(n % 2)

The code works by doing negations even/odd times using recursion. Even times negating true gives true . Odd times negating true gives false . Forget 42 check 1 and 2 .

If you open up console, you can see stack trace as well.

return even(2) =>
even(2) => odd(2 - 1)
odd(1) => return !even(1)
!even(1) => ! (odd(1-1))
! (odd(0)) => ! ( !(even(0))) => even(0)
even(0) => true

return even(1) =>
even(1) => odd(1 - 1)
odd(0) => !even(0)
!even(0) => !(true) => false

x is 0 with strictly equaling its type and value, I'm not sure why true is returned

This happens at the tail of recursion, this true is switched back and forth between true and false as each recursive call completes using the negation at !even(y)

 const res = ((n) => { const even = (x) => { if (x === 0) { console.log(x); console.trace(); return true; } else { const odd = (y) => !even(y); console.log(x); console.trace(); return odd(x - 1); } } return even(n) })(2) //=> true console.log(res); 

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