Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys,
I got a non responsive code of JavaScript type. The code works fine until it reaches line 4, than nothing else happen. There is no alert message showing.
here's the code:


JavaScript
var ageAsString = prompt("what is your age? ", "");
var age = number(ageAsString);
alert(age);
if (age < 40) {
    alert("You are so young...");
} else {
    alert("Ok");
}

alert("thank you");


the code is written in VS 2017.
Thanks,
Avri

What I have tried:

I've tried to run it on several browser and I got the same results.

If I run the code from within the tag, everything works beautifully.
The problem rises when I call this code by inserting a link to it
Posted
Updated 19-May-18 6:07am
v2

Case sensitivity is the problem :)

var age = number(ageAsString);


Should be:

var age = Number(ageAsString);
 
Share this answer
 
not sure where you got the function "number" from?

try parseInt

JavaScript
var ageAsString = prompt("what is your age? ", "");
var age = parseInt(ageAsString);
alert(age);
if (age < 40) {
    alert("You are so young...");
} else {
    alert("Ok");
}

alert("thank you");


you should look into debugging javascript:
JavaScript Debugging[^]
 
Share this answer
 
v2
Comments
Andy Lanng 17-May-18 8:33am    
Oh - I see where you got it from now ^_^
[no name] 17-May-18 8:35am    
parseInt works too though, so this is a good solution as well.
.
Actually there is no need to create an extra variable just and only to use it as a type modifier of the given value.

However you DO need to validate that user inputs something that is number type and not any other kind of string.

var ageAsString = prompt("what is your age? ", "");
var age = Number(ageAsString);

// you convert input string to Integer immediately, no need to create extra variable
var age = parseInt(prompt("what is your age?", "")); 


// you first check that age is indeed a number and not a Not A Number (NaN)

if (isNaN(age)) { // if age is NaN then alert the user to stop messing around

    alert("You have to insert a number mate")

// in any other case , the script continues to do your stuff
} else { 

    alert(age);

    if (age < 40) {
        alert("You are so young...");
    } else {
        alert("Ok");
    }

}

alert("thank you") // you are welcome

Now there is a catch, if you put let's say 23a it will pass as a number and not a NaN.

For these cases you'll have to make more sophisticated validators but for now I think you have already got the idea of how to make your script more solid.

.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900