Output Mechanics
Overview
JavaScript doesn't have a built-in print or output facility of its own. It relies on the environment (like the browser or Node.js) to display data.
When building web apps, you primarily use the console for debugging, alert() for urgent popups, and DOM manipulation to show text directly on the webpage.
Syntax
In modern development, console.log is your best friend for fixing bugs, and DOM manipulation is how you actually show data to users.
// 1. Console (Best for debugging)
console.log("Standard log");
console.error("Red error text");
console.warn("Yellow warning text");
console.table([{name: "Kartik", age: 22}]); // Prints a neat table
// 2. Alert (Pauses execution until dismissed)
alert("This is an alert box!");
// 3. Document (Writes directly to HTML - rarely used in modern apps)
document.write("Hello HTML!");
// 4. DOM Manipulation (The standard way to update UI)
document.getElementById("output").innerHTML = "Updated Text!";Common Pitfalls
- Using
document.write()after an HTML document is fully loaded will delete all existing HTML! Never use it in production. - Leaving
console.log()statements in production code. It can expose sensitive data and slightly slow down performance.
Interview Questions
If document.write() is executed after the page has finished loading, it will overwrite the entire HTML document. It also blocks the page from rendering if used synchronously.
Real-World Example
When debugging an API response, developers use console.table() to visualize arrays of objects easily.
const users = [
{ id: 1, name: "Alice", role: "Admin" },
{ id: 2, name: "Bob", role: "User" }
];
// This draws a perfect grid in the Chrome console!
console.table(users);Check Your Knowledge
Test your understanding of Output Mechanics with these quick questions.