PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 22, 2022

[FIXED] why does "Number" make the "else if" work here?

 November 22, 2022     javascript, multiple-conditions     No comments   

Issue

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!");
}

Solution

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!");
}



Answered By - Luke Storry
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing