Please enable JavaScript to use CodeHS

User Input in JavaScript

Learn how to accept user input in your JavaScript programs.

By Rachel Devaney

An important aspect of computer science is creating interactive programs for users. A large part of user interaction is allowing users to input information into a program.

In JavaScript, we use the prompt() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “ok,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.

Take a look at the following program to get a feel for how user input works. Run the program and explore with these guiding questions:

  • What do you notice about the type of value prompt() returns?
  • Why is it important to store the input the user gives in a variable?

User Input with CodeHS Library

You should have noted that prompt returns the user input as a string, but what if you want the user input to return a number instead of a string? You can convert the string to an integer using parseInt()…or you could just use the CodeHS library! The CodeHS JavaScript library includes the following commands:

readLine(prompt): Reads a string value from a user
readInt(prompt): Reads an integer value from a user
readFloat(prompt): Reads a float value from a user

Take a look at the following program. Enter the same number for each prompt. What is the difference between the two print statements? Why does this different occur?

Practice

You are putting together a report on the minimum wage in your state. Write a program that asks the user for the minimum wage of their state, calculates and prints the yearly salary. Assume a full work week (40 hours) for the entire year (52 weeks). You should use variables to store the minimum wage and the yearly salary. Hint: Choose your user input command carefully based on the type of data you are collecting!

Your output should look something like this:

What is the minimum wage in your state?
10.25

The average yearly salary for someone who works 40 hours per week for 52 weeks is $21320
Plain text