Learn how to accept user input in your JavaScript programs.
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:
prompt()
returns?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?
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: