Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!