Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain how you get false in this function expression?

Tags:

javascript

I understand the first part of the if, but isn't the second part stating "since 'n' is not equal to zero, return 'n' in the even function modified with the logical NOT(!) operator."? Doesn't that return 4 if I were to pass 5 as the argument to fn();?

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

fn(5); //=> false
like image 202
Antonio Pavicevac-Ortiz Avatar asked Dec 08 '22 06:12

Antonio Pavicevac-Ortiz


1 Answers

even(n) is always the opposite of even(n-1).

As even(0) is true, even(1) is false and so on : all multiples of 2 give true and odd numbers give false.

A simple way to see it might be to log [0,1,2,3,4,5].map(even).


Just in case you were really looking for a way to know if a positive integer is even, the solution you show is very very inefficient and the recursion results in a call stack explosion for any big number. Here's a more reasonable solution :

function even(n){
    return !(n%2);
}
like image 60
Denys Séguret Avatar answered Apr 27 '23 00:04

Denys Séguret