User Input and Formatting
Learn JavaScript’s prompt() function and basic formatting by building a receipt generator that lets the cashier enter details directly, without editing the code.
The project
We’ll go back to the POS system one last time. In the previous lesson, we entered prices, quantities, and names directly into the JavaScript code. That worked fine while we were coding, but it’s not how real systems usually work.
But here’s the problem: the cashier isn’t a coder. They don’t want to dig into code, find variables, and change values. They just want to type in the customer’s details and prices while the customer waits.
You’ve been hired to create a smarter version of this point-of-sale system, one where the cashier simply enters the quantities and prices at the command line when the app is running, and the program automatically calculates and prints the receipt. The cashier will not need to look at the code. This is what the receipt looks like:
The programming concept
The new concept for today is user input.
So far, we’ve only displayed information using console.log()
. But what if we want the user, like our cashier, to type something in? That’s where user input comes in. JavaScript gives us a built-in function called prompt()
. It shows a small dialog box where the user can enter information.
A key thing to remember: