Input/Output Flashcards
What is ‘console.log()’?
This built-in function takes any JavaScript value, regardless of type, and logs it to the console
There are other ways to send messages to the console in node, but console.log works in both node and most browsers
Can we ask the user to provide her name and greet her with a message that uses the name she entered?
Yes, we can. Node.js has an API called readline that lets JavaScript programs read input from the command line.
However, the API isn’t straightforward or simple: it requires an understanding of asynchronous programming and higher-order functions
What is happening in this code?
Line 1 uses Node’s built-in require function to import readline-sync into your program. It returns the library as an object, which we assign to the rlSync variable.
In line 2, we use rlSync to call the question method. This method displays its string argument, then waits for the user to respond. When the user types some text and presses Return, it returns that text to the program. Here, we assign that text to the variable name and use it to display a personalized greeting.
Why do we need to use the Number method?
rlSync.question() still returns a string, but this time we coerce each string to a number with the Number function. With numbers in both variables, JavaScript adds them arithmetically.
Browsers
Browsers provide an environment that differs radically from that of Node.js: browser users must interact with JavaScript programs in an entirely different way.
Working with a browser’s input controls requires a working knowledge of the Document Object Model (DOM)
However, most browsers implement the prompt function which lets a program ask for and obtain text-based input from the user
Prompt function in browsers
We need an HTML file and JavaScript file to re-implement our personalized greeting program for the browser.
The prompt function works much like rlSync.question: it waits for the user to input some text and click the ‘OK’ button, and then returns the user’s input as a string. As with the Node.js version of this program, we can assign the return value to a variable and use it later in the program. In this example, our program uses the string to build a personalized greeting message and logs it to the console.
What is at the heart of every computer program?
This input/output cycle.
After all, software that accepts no input and provides no output is useless.