Simple else if not being executed

Simple else if not being executed
0.0 0

#1

New to Javascript but not programming in general and my else if won’t execute when I type in 31. Anyone know why this wouldn’t work?

var age = prompt(“Enter age”);

if(age >= 21) {
alert(“Good”);
}

else if (age === 31) {
console.log(“Perfect”);
}


#2

You are using the strict equality operator, so since age is a string (from the prompt) and 31 is a number, they are not strictly equal. If you use == instead, the else if condition will evaluate to true and “Perfect” will be displayed to the console.

Actually, the main reason the console.log does not execute is that if you enter 31 for the prompt, your first if statement evaluates to true, because age gets coerced into a number and since 31 is greater than or equal to 21,


#3

I swore the guy in the tutorial I watched said use “====” all the time because it’s safer. Anyhow, thanks.


#4

It is only “safer” if you want to only compare numbers with other numbers.


#5

It’s still not working for me. Nothing appears in the console when == is used.


#6

See my 2nd comment of my first reply to you.


#7

You’re using strict equality which mean the types are important when the values are compared. The result of calling prompt('Enter age'); is a string [1]. Try this on your browser console:

typeof(prompt('Enter age')); // type 31 and press enter
// "string"

But even if you make it just a simple equality operator (==), the condition in your if statement (age >= 21) will be true if age is '31' because of type coercion [2].

'31' >= 21
// true

So your else if clause is skipped.

[1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
[2]: https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839


#8

Got it to work doing this. Can’t say I’m a fan of how Javascript handles this.

Edit: Didn’t know there was a typeof method. Good to know. I literally picked up this language for the first time like an hour ago.

var age = Number(prompt("Enter age"));

if(age <= 21) {
	alert("Good");
}

else if (age == 31) {
	console.log("Perfect");
}