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

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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