1

I am checking to see if the product of 2 given values is a number or not. If product is NaN, i want to prompt an error.

The problem is that for all the values (even if it is NaN) it doesn't throw an error.

here is my code

function multiply (val1, val2) {
if ((val1 * val2) === NaN) {
alert('Please provide number for multiplication');
} else {
return (val1 * val2);
}

}

user3566643
  • 535
  • 1
  • 4
  • 8

3 Answers3

3

You can't use ordinary comparison operators to check for NaN. Use isNaN()

if (isNaN(val1 * val2)) { 
Pointy
  • 405,095
  • 59
  • 585
  • 614
1

Do this instead

if (isNaN(val1 * val2))
Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63
0

Another way you could do it is part of an unusual feature of NaN. It is the only thing in javascript that is not equal to itself. Which is exactly why your code is not working because NaN will never equal NaN, so you could reverse your logic

function multiply (val1, val2) {
    var product = val1 * val2;
    if (product != product) { //i.e. NaN
        alert('Please provide number for multiplication');
    } else {
        return product;
    }
}

check if product does not equal product will only resolve to true if it is NaN.

OJay
  • 4,763
  • 3
  • 26
  • 47
  • this will work, but it will likely confuse folks who have to maintain it later :) – Andbdrew Aug 13 '14 at 22:39
  • @Andbdrew - Seems an ironic comment, since you suggested it in a comment yourself. Adding a comment in the code (as I did) I'm sure will help people that might become confused. Its a standard part of the javascript language – OJay Aug 13 '14 at 22:41
  • 1
    I added it as a comment instead of an answer because, while it is true and will work, it probably shouldn't be used directly in code that might need to be fixed late at night by someone who's not super familiar with javascript. Just because you CAN do it, doesn't mean you SHOULD :) – Andbdrew Aug 13 '14 at 22:48