Users interact with computers in many ways. Your keyboard, mouse or trackpad, microphone, touchscreen, and stylus are all different ways that we provide input to the computer. We click on things we see or use keys on the keyboard to control an object or enter text. We're going to start with entering text.
Many programming languages have a chunk of code built-in for listening to the keyboard. In Python the command is input()
, in Java it's System.console().readLine();
but in JavaScript it's prompt()
.
We're not using browser JavaScript, we're using NodeJS. So we need to install the prompt code. You only have to do this once on your computer.
In a terminal, make sure you have npm installed by running:
sudo apt update
sudo apt install npm
Install the prompt-sync code library by running:
npm install prompt-sync
Now you're ready to use prompt()
in your code!
We have to tell NodeJS that we want to use the prompt-sync
library in our code. For this, we will add the following to the top of our code file - it declares the prompt()
command:
const prompt = require('prompt-sync')();
After preparing the code, we can ask the user to enter something and store it in a variable.
Here are a few examples:
/* main.js */
const prompt = require('prompt-sync')();
let age = prompt("How old are you? ");
console.log("You said you are", age, "years old.");
let name = prompt("What is your name? ");
age = prompt("How old is your dog? ");
Even the age
variable in the example above will be considered a word, no matter if the user enters a number. This causes a problem with math.
Try this in your own console:
let age = prompt("How old are you? ");
console.log(age + 5); // What do you think will print?
We can (try to) convert a String to a number:
// We have a few options
let my_value = Math.PI;
my_value = parseInt(my_value); // 3
my_value = parseInt("year2022"); // NaN
my_value = parseInt("2022year"); // 2022
my_value = parseFloat("3.14"); // 3.14
my_value = parseFloat("56"); // 56
my_value = Number("year2022"); // NaN
my_value = Number("2022year"); // NaN
my_value = Number("3.14"); // 3.14
Examples:
let age = parseInt("twelve");
console.log(age); // NaN
let year = parseInt("2022.5");
console.log(year); // 2022
We can get the length of a String:
let name = "Mr. Squirrel";
console.log(name.length) // 12
"St. Matthew High School".length; // 23
let my_string = " spa ce!".length; // 8
Time to try the task.
🐿️