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