JS Basics
JavaScript Output
Learn the different ways JavaScript can display output: console, alert, document write, and innerHTML.
JavaScript Output
JavaScript can "display" data in different ways:
- Writing into an HTML element, using
innerHTMLortextContent - Writing into the HTML output using
document.write() - Writing into an alert box, using
window.alert() - Writing into the browser console, using
console.log()
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content.
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display data. The console is your primary debugging tool in JavaScript.
Example
javascript
// 1. innerHTML - Update DOM element
document.getElementById("output").innerHTML = "<strong>Updated!</strong>";
// 2. textContent - Safe text (no HTML parsing)
document.getElementById("text").textContent = "Safe text output";
// 3. console methods
console.log("Regular log");
console.warn("Warning message");
console.error("Error message");
console.table([{name: "Alice", age: 25}, {name: "Bob", age: 30}]);
console.time("operation");
// ... some operation
console.timeEnd("operation");
// 4. alert / confirm / prompt (browser only)
// alert("Hello!");
// const ok = confirm("Are you sure?");
// const name = prompt("Your name?");
// 5. document.write (use rarely)
// document.write("This writes to the document");Try it yourself — JAVASCRIPT