Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda