EDIT : To be short:
a% sign -
in front of a numeric variable what it does is change that variable.
That is, if the variable is positive, it becomes negative. If the variable is negative, it becomes positive. Example:
n = 5
implies that -n = -5
n = -5
implies that -n = 5
Original reply
In the defined function isEven
uses recursion for the natural numbers i positive .
Notice that we have 4 cases defined in the function. 2 bases and 2 continuation.
In both base cases, the end of the function is defined, where if it is arrived with n=0
then it returns true
and if it is reached with n=1
it returns false
.
The operation of the function itself is to call the same function by subtracting 2 from each iteration until it reaches 0
or 1
(what the last function does).
As it is only defined by positive numbers, there is a base case of input that calls the function isEven
if the number we want is negative. To give an example:
1st iteration: isEven(3)
is called
2nd iteration: isEven(1)
is called
3rd iteration: How n=1
returns false
.
- If we start from any negative number, for example,
n=-5
, which is the specific case you ask:
1st iteration: isEven(5)
is called
2nd iteration: isEven(3)
is called
3rd iteration: isEven(1)
is called
4th iteration: How n=1
returns false
.
So doing a isEven
of a negative number is the same as doing a isEven
of the same number but positive (and with 1 more level of recursion).
Of the 3 example functions given in the book the last console.log(isEven(-1));
is the only one that enters in that specific case ( n<0
) and then calls isEven(1)
To finish simply commenting that it is much easier to use the module to calculate if a number is even or odd:
function isEven(n)
{
return n%2==0;
}