'How to return a message in js if you forget to put the quotes in a argument string

I'm new to JavaScript and following a course, I've tried to look for answers on other posts but I couldn't find anything similar, hopefully, I didn't miss any.

I have this code:

const calculateWeight = (earthWeight, planet) => {

    if (typeof earthWeight !== "number") {
        return "The earth weight must be a number!!";
    }

    if (typeof planet !== "string") {
        return "The planet will accept only letters!!";
    }

    planet = planet.charAt(0).toUpperCase() + planet.slice(1).toLowerCase();

    if (planet === "Mercury") {
        return earthWeight * 0.378;
    } else if (planet === "Venus") {
        return earthWeight * 0.907;
    } else if (planet === "Mars") {
        return earthWeight * 0.377;
    } else if (planet === "Jupiter") {
        return earthWeight * 2.36;
    } else if (planet === "Saturn") {
        return earthWeight * 0.916;
    } else {
        return "Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn."
    }
}

console.log(calculateWeight(100, "Jupiter"));

On the first and second if statements, I've used the typeof to return a message in case the argument for earthWeight is not a number and the argument for planet is not a string in the very last line of the code where I run the function.

It works if I put a string instead of a number and vice-versa, but if I put a word without quotes, simulating a mistake, I just get an error, is there any way to actually return a message?

Looking at MDN documentation, it seems that a word without quotes should be typeof "undefined" so I thought that changing that code like this, would help:

if (typeof earthWeight !== "number" || typeof earthWeight === "undefined") {
    return "The earth weight must be a number!!";
}

if (typeof planet !== "string" || typeof planet === "undefined") {
    return "The planet will accept only letters!!";
}

Is that something possible?

Kind regards.



Sources

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

Source: Stack Overflow

Solution Source