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

209
Visualizações
Why type errors are not caught by IF Statement parameters in JavaScript?

Why is it that comparison operators do not consider empty strings or non-integers to be errors?

Example:

        var x = “”;

        if (x>=1 && x<=10){
            console.log(x);     //validation code: error is expected to be thrown as variable x is not an integer
        } else {
            console.log(“Error: ” + x);
        }

Coding language: JavaScript (vanilla)
Skill level: Beginner
Editor: Visual Studio Code
OS: Windows 7

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

From the MDN: "JavaScript is a loosely typed and dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types"

In the case of comparisons, this has a side-effect: "In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison."

When comparing a string to a number, Javascript will try to convert that string into a number value for the comparison. Empty strings are considered to have the number value 0.

If you separate your if-statement into two separate comparisons, you'll see that:

x >= 1 is false (because 0 is less than 1)
x <= 10 is true (because 0 is less than or equal to 10)

This implicit type casting is the reason you won't get a type error. But since both conditions of your if-statement cannot be true at the same time for an empty string, you will get the error you log from the else branch.

about 4 years ago · Juan Pablo Isaza Relatório

0

In my opinion, x value similar to NULL and comparison operators do not consider the condition x >=1 && x<=10 as compare with NULL. Again, it's just my opinion.

var x = “”; // x is similar to NULL here 

    if (x>=1 && x<=10){
        console.log(x);     //validation code: error is expected to be thrown as variable x is not an integer
    } else {
        console.log(“Error: ” + x);
    } here
about 4 years ago · Juan Pablo Isaza Relatório
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