Search code examples
javascriptnumbersnantypeof

Why is typeof === 'number' not the same as !isNaN(number)


I have the following code to solve this problem: https://leetcode.com/problems/letter-case-permutation. The end result should be ["a1b2","a1B2","A1b2","A1B2"] for the string "a1b2"

function letterCasePermutation(str) {
    const res = [];
    helper(str, res, 0, "");
    return res;
}

function helper(str, res, i, slate) {
    const char = str[i];
    const parsed = parseInt(char, 10);
    //base case
    if(i >= str.length) {
        res.push(slate);
        return;
    }

    // if(!isNaN(parsed)){
    if(typeof parsed === 'number') {
        slate = slate += char;
        helper(str, res, i+1, slate)
    }
    // check for letter
    else if(char.toLowerCase() !== char.toUpperCase()) {
        slate = slate += char.toUpperCase();
        helper(str, res, i+1, slate);

        slate = slate += char.toLowerCase();
        helper(str, res, i+1, slate);
    }
}

letterCasePermutation("a1b2"); //[ 'a1b2' ]

The code above doesn't work because when I do:

console.log(typeof parsed === 'number') // false

The result is always false, even if it is a number (1 and 2). However, when I changed this line:

if(typeof parsed === 'number') {

to:

if(!isNaN(parsed)){

It works perfectly. Why is that?


Solution

  • The reason is because NaN is a number! This is one of those weird gotchas with javascript that bites all of us in the butt every now and then. The correct way to handle this is by using !isNaN(...) as you did above.

    Read more: https://claritydev.net/blog/what-is-the-type-of-nan/