0

I have this code sample:

if (!params || params?.page == null) {
        console.log('condition 1');
        inputParam = 1;
    } else if (parseInt(params.page) == NaN) {
        console.log('condition 2');
        inputParam = 1;
    } else if (parseInt(params.page) < 0 || parseInt(params.page) > 42) {
        console.log('condition 3');
        inputParam = 1;
    } else {
        console.log('condition else');
        inputParam = params.page;
    }
    console.log(params.page);
    console.log(parseInt(params.page));
    console.log(inputParam);
    console.log(parseInt(params.page) === NaN);
    const processedParam = parseInt(inputParam);
    console.log(processedParam);

I've been running this in a node app that I have. I get this in my console.

condition else
oh
NaN
oh
false
NaN

Why is else if (parseInt(params.page) == NaN) { not catching, and why is console.log(parseInt(params.page) === NaN); reading false when it's clearly supposed to be true?

ChristianOConnor
  • 820
  • 7
  • 29
  • 1
    Does this answer your question? [Is NaN falsy? Why NaN === false returns false](https://stackoverflow.com/questions/22600248/is-nan-falsy-why-nan-false-returns-false). It is already described how NaN behaves when compared. So to compare NaN there are other possible options you can use. – MORÈ Dec 02 '22 at 03:14

1 Answers1

0

I fixed it. I changed my code to this:

if (!params || params?.page == null) {
        console.log('condition 1');
        inputParam = 1;
    } else if (isNaN(params.page)) {
        console.log('condition 2');
        inputParam = 1;
    } else if (parseInt(params.page) < 0 || parseInt(params.page) > 42) {
        console.log('condition 3');
        inputParam = 1;
    } else {
        console.log('condition else');
        inputParam = params.page;
    }
    const processedParam = parseInt(inputParam);

and my terminal printed condition 2 when params.page was set to "oh"

ChristianOConnor
  • 820
  • 7
  • 29