Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda