Turning Learners Into Developers
Codekilla
CODEKILLA
back to course
Lesson 03 / 1153%· free preview
Basics3/13

JS Input & Output

Browser dialogs (`alert`, `prompt`, `confirm`) for input, and the five ways JS shows output — `console.log`, `alert`, `document.write`, `innerHTML`, `window.print`.

Definition

JavaScript talks to users in two directions:

Input — three blocking browser dialogs let JS read a value the moment it's needed:

  1. alert(msg) — pops a modal with an OK button (returns undefined).
  2. prompt(msg, default?) — text-input dialog, returns the typed string (or null if cancelled).
  3. confirm(msg) — OK / Cancel dialog, returns true / false.

Output — five common channels for showing results:

  1. console.log() — writes to the DevTools / Node terminal. The developer's go-to.
  2. alert() — pops a modal dialog. Loud and intrusive, but unmistakable.
  3. document.write() — writes directly into the HTML document (during page load).
  4. element.innerHTML — replaces the inner HTML of any DOM element. The standard for real apps.
  5. window.print() — opens the browser's print dialog.

Most production code uses innerHTML (or React's equivalent). console.log is for debugging, alert is for emergencies, document.write is a relic. Browser dialogs (alert/prompt/confirm) block the page — modern UIs use <dialog> or in-app modals instead.

Browser Dialogs — Quick Reference
javascript
alert("Hello!");                 // OK button — returns undefined
const name = prompt("Name?");    // text input — returns string | null
const ok   = confirm("Sure?");   // OK / Cancel — returns boolean
javascript
// Tiny demo — runs in any browser console
const name = prompt("What's your name?", "Aarav");
if (name && confirm(`Hi ${name}, ready to start?`)) {
  alert(`Welcome, ${name}!`);
} else {
  console.log("User cancelled.");
}
Choose an Output Method
MethodWhere it showsUse case
console.log()Browser DevTools / Node terminalDebugging, structured inspection
alert()Modal dialog over the pageQuick "are you sure?" confirmations
document.write()Inline in HTML (during load only)Tutorials, never in production
el.innerHTMLInside a DOM elementReal apps — dashboards, forms, lists
window.print()OS print dialogPrint invoices, certificates, receipts
Four Output Methods in One Page

Step 1. Create a file output.html:

html
<!DOCTYPE html>
<html>
<body>
  <h2>JavaScript Output Demo</h2>
  <p id="demo">Loading…</p>

  <script>
    // 1. Console — open DevTools (F12) to see this
    console.log("Hello from console.log");

    // 2. innerHTML — replaces the <p> contents
    document.getElementById("demo").innerHTML = "Hello, Codekilla!";

    // 3. document.write — appends to the page during load
    document.write("<p>Written by document.write</p>");

    // 4. alert — uncomment to see the popup
    // alert("Hello, alert!");
  </script>
</body>
</html>

Step 2. Open the file in a browser (double-click, or right-click → Open with).

Output (visible on the page):

JavaScript Output Demo
Hello, Codekilla!
Written by document.write

Output (in DevTools console after pressing F12):

Hello from console.log
What Just Happened?
  • The browser parsed the HTML top to bottom.
  • console.log printed to the developer console (a separate panel).
  • getElementById("demo").innerHTML = "..." swapped the paragraph's content with the new string.
  • document.write appended new HTML while the page was still loading. Calling it after load nukes your whole page — that's why it's avoided in real apps.
innerHTML vs textContent
PropertyRendersRisk
innerHTMLParses string as HTML (tags, styles, even <script>)XSS if untrusted input is interpolated
textContentPure text, no HTML parsingSafe by default — prefer for user-supplied data
javascript
el.innerHTML  = "<b>Hi</b>";     // renders bold
el.textContent = "<b>Hi</b>";    // renders the literal characters
console — Debugging Toolbox
CallUse
console.log(...)Standard print
console.warn(...)Yellow warning
console.error(...)Red error with stack trace
console.info(...)Info message
console.table(arr)Pretty-print arrays / objects
console.dir(obj)Tree view of an object
console.group("name") / .groupEnd()Nested log blocks
console.time("t") / .timeEnd("t")Measure elapsed ms
console.assert(cond, msg)Log only when cond is false
javascript
console.table([{ id: 1, city: "Mumbai" }, { id: 2, city: "Delhi" }]);

console.time("loop");
for (let i = 0; i < 1e6; i++);
console.timeEnd("loop");          // loop: 4.2 ms
Online Compiler — Skip Setup

Don't want to set up an HTML file? Use Codekilla's online JavaScript compilerconsole.log output appears directly in the run pane.

Common Mistakes
  • Calling document.write() after the page loads — it overwrites your entire page with the string.
  • Trusting innerHTML with user input — pasting raw HTML opens XSS attacks. Use textContent for user-supplied strings.
  • Missing the DevTools panelconsole.log only appears once you press F12 and click the Console tab.
  • Confusing console.log() with print() — JavaScript has no built-in print() for stdout (Python lingo). It's console.log.
  • alert() flooding — calling alert in a loop locks the browser. Reserve it for one-off confirmations.
  • Treating prompt() return as a number — it's always a string (or null). Wrap with Number(...) before math.
  • Leaving alert debug calls in production — embarrassing.
Interview Questions

Practice Exercises
  1. Three Outputs — Build an HTML page that uses console.log, alert, and innerHTML to display "Hi {your_name}". Hint: target a <p id="demo">.
  2. Safe vs Unsafe — Write a script that takes userInput = "<img src=x onerror=alert(1)>" and inserts it into the page using innerHTML, then again using textContent. Observe what happens. Hint: open DevTools to see the difference.
  3. Pretty Table — Console-table the array [{name: "Aarav", score: 92}, {name: "Bhavna", score: 87}]. Hint: console.table(arr).
  4. Prompt Calculator — Use two prompt() calls to read numbers from the user, then alert() the sum. Hint: convert with Number(...) first.
  5. Confirm Guard — Show a confirm("Delete this item?") and only console.log("deleted") when the user clicks OK. Hint: returns a boolean.

💡 Think Like a Programmer: Default to textContent when displaying any user-supplied string. Switch to innerHTML only when you specifically need to render trusted HTML — and even then, sanitise first with a library like DOMPurify. For real input UI, prefer in-app modals or <dialog> over the blocking browser dialogs.

AI-powered recap

Quick recap quiz?

We'll generate 5 MCQs from this lesson and check your understanding instantly. Takes ~30 seconds.

# program

Program

JavaScript
const name = prompt("Name?", "Aarav");
console.log("Hello", name);
Ready to move on?
// example library
Want more hands-on snippets in JavaScript?
Browse 2 runnable examples · across 1 chapter · short, copy-paste-friendly · grouped by topic
Explore examples
// did you know?
One surprising fact before your next lesson
Bite-sized programming facts that make your next coffee-break explanation land.
Did You Know
// feedback.matters()
Did this lesson help you?