why does “Number” make the “else if” work here?

Tags: ,



I have a task to play a little with if/else if. i don’t understand why, when I write my code like the example below, the “else if(age === 18)” part doesn’t work. it shows up as “undefined”. the other 2 work. But, when i add (Number(age) at all of them, it works. Why is that? why can i use 2/3 without “Number”, but i need it to use 3/3?

var age = prompt("Please type your age!");
if (age < 18) {
    alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
    alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
    alert("Powering On. Enjoy the ride!");
}

Answer

It is because prompt returns a string.

The operators < and > will allow you to compare a string to a number, by pre-converting the string to a number and then comparing them. Read this article for more info on this, called “Type Coersion” in JS.

The === operator however will not do this type coercion/conversion, it will directly compare "18" with 18 and return false.

To fix this, you can instead use the other equals operator, ==, which does include type coercion.

However, a better way of doing it would be to check the input is definitely a number, like this:

var age = Number(prompt("Please type your age!"));

if (Number.isNaN(age)) {
    alert("Try again with a number");
} else if (age < 18) {
    alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
    alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
    alert("Powering On. Enjoy the ride!");
}


Source: stackoverflow