Search code examples
javascriptparseint

Checking if variable is an Integer in Javascript


I'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.

This code DOES NOT WORK FOR ME ON CHROME.

var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");

if (age == parseInt(age, 10))
    alert("data is integer")
else
    alert("data is not an integer")

Whether I enter a string or integer in my prompt box, it always display the "data is not an integer" message.


Solution

  • prompt will always return a string so in your case:

    var integerAge = parseInt(age);
    
    if(!isNaN(integerAge) && age === '' + integerAge)
        alert("data is integer")
    else
        alert("data is not an integer")
    

    In the case of an age, you'll also probably check it's a positive integer with some integerAge >= 0 or custom minimum and maximum in the next validation step.