Input

So far in our work, we have been using hard-coded numeric values for our variables that we typed directly into the source code of the programs. However, we would like to be able to execute our algorithms against different values. It would be inconvenient for the user of our program to modify the source code every time the numeric inputs to the algorithm change. We can use the ask() built-in function to prompt the user to enter values for our variables.

Prompting User For Input

To prompt the user to enter a value, use the ask() function:

let userName = ask("What is your name?")

The ask() function will show an input field next to the console, with the text prompt that was provided as the argument. When the user enters some text in the input field, the ask() function will return the text back to the program as a string.

What is a function?

ask() is an example of a built-in function. We have not encountered a function just yet, but for now it will be sufficient to think of a function as a "command that calculates a value". The values in parentheses are the function arguments and the value that is calculated is called the return value.

String Input Example

When this program runs, it will ask the user to enter a name and then print a greeting with that name to the console:

console

Numeric Data and Other Types

We saw that the value returned from the ask() function is a string. However, we might want to receive numbers from the user input, as well. In order to do it, we need to convert the string that we receive from ask() into a number. The easiest way to do so is to provide a type specifier to the let statement:

let number age = ask("What is your age?")

When number is provided as the type specifier, the string return value from ask() is automatically coerced into the numeric data type. If the string does not represent a legal number literal, an error will be produced.

Numeric Input Example

console

Remember that ask() always returns a string, and you must always use the number type in your variable definition if you want to treat it as a number.

Exercises

Calculate My Age

Write a program that prompts the user for a year of birth and calculates their current age based on this number. What happens when you enter a year that is in the future?

console

Back (020-variables)
Forward (030-comparisons)