mardi 21 juin 2016

What is a better way to get a even number?

So I have been reading this book named: Eloquente JavaScript, and to be true somethings in this book seems quite complex. There was this challenge were I had to wright a function that showed true or false depending if the value was even or not. My version is quite shorter then the one from the book. What should be the best way of doing this? Also why did he do it like this?

Eloquente JavaScript code:

function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);
}

console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));

My own code:

function even(num) {
      if (num % 2 == 0){
         return true;
      }
      else{
         return false ;
      }
  };

  console.log(even(17));
  console.log(even(10));
  console.log(even(-33));
  console.log(even(-40));

Aucun commentaire:

Enregistrer un commentaire