简体   繁体   中英

What is the problem in this recursive javascript function? [JS]

Hi to all I am trying to make a program in order to output when a number is Even using recursive calls. Can anybody please say me why it doesn't work as I expected?.

const isEven = num => {
  if (num === 0) return true;
  else if (num === 1) return false;
  //console.log(num);
  isEven(num-2);
}

isEven(16); // Epected Log: 0 but instead it returns undefined

Because for arguments different than 0 or 1 there is no return value. The last line:

  isEven(num-2);

should be

  return isEven(num-2);

You are not returning a value.

Change:

isEven(num-2);

To:

return isEven(num-2);

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