'How to return NaN

I'm working on a codewars problem-here's the question:

-Write a function that accepts two integers and returns the remainder of dividing the larger value by the smaller value. -Division by zero should return NaN.

I have the first part figured out, but how do I return NaN if I divide by 0? I don't know a lot about NaN and I'm pretty new to JavaScript.

function remainder(n, m){
  if (n > m) {
    let answer = n % m;
    if (m === 0) {
      return undefined;
    }
    else {
      return answer;
    }
  }
  else if (m > n) {
    let answer = m % n;
    if (n === 0) {
      return undefined;
    }
    else {
      return answer;
    }
  }
  else {
    let answer = n % m;
    return answer;
  }
}

Edit: solved, answer is below



Solution 1:[1]

This is my answer (with help from the comments on my question), and it worked. Thank you for your help!

function remainder(n, m){
  if (n > m) {
    let answer = n % m;
    if (m === 0) {
      return NaN;
    }
    else {
      return answer;
    }
  }
  else if (m > n) {
    let answer = m % n;
    if (n === 0) {
      return NaN;
    }
    else {
      return answer;
    }
  }
  else {
    let answer = n % m;
    return answer;
  }
}

Solution 2:[2]

The problem is that % is not the divider syntax, but this is /.

I created a basic example for you: In this example, the console logs "divider is 0"

function divider(up, down) {
  if (down == 0) {
    console.log("divider is 0");
    return NaN
  } else {
    console.log(up / down);
  }
}

divider(5, 0);

But here, it will log 2.5

function divider(up, down) {
  if (down == 0) {
    console.log("divider is 0");
    return NaN
  } else {
    console.log(up / down);
  }
}

divider(5, 2);

Solution 3:[3]

Welcome to our community!

NaN stands for Not-a-Number and it is a property of the global object(in order to understand more about the global object, I would recommend reading about Scopes).

You could access NaN like this:

window.NaN => from a browser
Number.NaN
NaN

If you want to check if a number is NaN you could use: isNaN.

If you want to use it in a function you can just do

    function test(x){
      if(isNaN(x)){
        return NaN;
      }
      return x;
    }

To come back to your problem, you could do something like this:

    function calculateRemainder(a,b){
      return a>b ? a % b : b % a
    }

Where % is known as the remainder operator about which you can read more here. This operator returns NaN if you try to divide by 0 or to operate with Infinity.

The following operations return NaN:

NaN % 2
Infinity % 0
10 % 0
Infinity % Infinity

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Emiel VdV
Solution 3