3.3 Input and Output
Programs need to communicate with users. In browser JavaScript, the most basic outputs are console.log(), alert(), and changing page content. The most basic inputs are form fields, events, and sometimes prompt().
console.log()
console.log() prints text or variable values to the developer console. It is mainly a learning and debugging tool.
let name = "Leaf";
let age = 18;
console.log(name);
console.log(age);
console.log("Name:", name, "Age:", age);Output:
Leaf
18
Name: Leaf Age: 18String formatting
JavaScript can join values into strings in several ways.
String concatenation uses +:
let language = "JavaScript";
console.log("I am learning " + language + ".");Template literals use backticks and ${...} placeholders:
let length = 10;
let width = 5;
let area = length * width;
console.log(`Area = ${length} * ${width} = ${area}`);Template literals are usually easier to read when a string contains several values.
prompt() and type conversion
prompt() asks the user for text. Important: it always returns a string or null, even if the user types digits.
let input = prompt("Radius:");
let radius = Number(input);
let area = Math.PI * radius ** 2;
console.log(`Area = ${area.toFixed(2)}`);One possible run:
Radius: 5
Area = 78.54Number(input) converts the input string into a number. Math.PI is JavaScript's built-in value for pi. toFixed(2) formats a number with two decimal places.
Page input and output
In real front-end work, you usually read from form fields and output by updating the DOM.
const input = document.querySelector("#name");
const output = document.querySelector("#message");
input.addEventListener("input", () => {
output.textContent = `Hello, ${input.value}!`;
});This pattern is the bridge between programming basics and interactive web pages.