Lesson Monday

The most common error beginning JavaScript students experience is attempting to call functions meant for numbers on strings. This happens especially frequently because all values returned from a prompt are saved as strings. Even if the user enters a number into a prompt without quotation marks! Unfortunately, this is simply how JavaScript works.

If we wanted to collect a value from a user with prompt(), and perform arithmetic with this value, we would need to convert it into a number with JavaScript's parseInt() function. If not, we would receive some very unexpected output.

Common Data Type Errors

Here's what can happen if you don't parse integers correctly. In the example below, we use prompt() to ask the user how old they are. The user enters 35. We then attempt to perform some arithmetic on age:

> var age = prompt("Enter your age: ");
> age + age;
3535

Remember, all values returned from a prompt are strings! So, even though the user entered a number, age is actually equal to the string "35". Since the + operator can be used to concatenate strings age + age actually returns"3535", instead of 70.

Using parseInt() to Avoid Data Type Errors

To make a string a number, we parse it using the parseInt() function like this:

> var number = parseInt("5");
> number;
5

So, to change our age from the example above into an integer, we do the following:

> var inputtedAge = prompt("Enter your age: ");
> var age = parseInt(inputtedAge);
> age + age;
70

Alternatively, the code does the exact same thing on a single line. Here we immediately pass the string returned by the .prompt() function as the argument to the parseInt() function:

> var age = parseInt(prompt("Enter your age: "));
> age + age;
70

Additional Information

Note: The Int part of parseInt() is short for integer, which means it's a whole number. If we wanted to convert something into a number with a decimal, we'd use parseFloat():

> var pi = "3.14";
> parseFloat(pi);
3.14

Floating point numbers are simply numbers with decimals. If you're parsing a whole number, use parseInt(), if you're parsing a number containing a decimal point, use parseFloat().

Summary


  • All values returned from a prompt are saved as strings.

  • To collect a value from a user with prompt(), and perform arithmetic with this value, we would need to convert it into a number with JavaScript's parseInt() function. If not, we would receive some very unexpected output.

  • The Int part of parseInt() is short for integer, which means it's a whole number. If we wanted to convert something into a number with a decimal, we'd use .parseFloat() -

  • Floating point numbers are numbers with decimals. We'll explore these more later!