Programs display results and sometimes receive user input. To preserve the output–formatting–input–practice progression used by the C, C++, and Java courses, this lesson uses the browser console's console.log() and the browser-provided prompt() function.
Output with console.log
console.log() writes one or more values to the developer console. Put literal strings in quotes; do not quote a variable name when you want its value. In a string, \n is a newline, \t is a tab, \" is a double quote, and \\ is a backslash.
const course = "JavaScript";
console.log("Hello World!");
console.log("Course:", course);
console.log("\"Hello\nWorld\"");KNOWLEDGE QUIZ
Joining and formatting values
A template literal uses backticks and inserts a value with ${expression}. Call toFixed() when a number needs a fixed count of decimal places; it returns a formatted string.
const length = 10;
const width = 5;
const area = length * width;
console.log(`Area: ${length} × ${width} = ${area.toFixed(2)}`);KNOWLEDGE QUIZ
Input with prompt
In a browser, prompt() opens an input dialog and returns a string; Cancel returns null. Typing 5 still produces "5". Use Number() before arithmetic and Number.isNaN() to detect a failed conversion.
const rawRadius = prompt("Radius:");
const radius = Number(rawRadius);
if (Number.isNaN(radius)) {
console.log("Enter a valid number");
} else {
const area = Math.PI * radius * radius;
console.log(`Area: ${area.toFixed(2)}`);
}prompt is a browser Web API; Node.js uses different APIs for terminal input. The Lab uses a repeatable simulated interface rather than opening real dialogs.
KNOWLEDGE QUIZ
Output Lab Bench
Run the three code cards in order and watch how each statement changes the terminal.
Calculate the distance between two points
Read two coordinate points and print the planar distance.
- Read x1, y1, x2, and y2 as four floating-point numbers.
- Apply the distance formula to compute the result.
- Print the distance rounded to two decimal places.
Build a temperature record card
Read one Celsius value, store it in clearly named variables, convert it to Fahrenheit, and print a compact report.
- Read one Celsius value with prompt() and Number().
- Store the Fahrenheit result in a variable named fahrenheit.
- Create a string variable named reportTitle and print it together with the converted value.