JavaScript Tutorial
JavaScript Output
Show a result with console.log, textContent, or an alert. Pick the one that matches the job.
Pick the output that matches the job
JavaScript can write to the console, change the page, or pop a dialog. Those are not the same place. If you log a message and stare at the heading, nothing will happen there.
| Tool | Where it appears | Use it for |
|---|---|---|
console.log | The console pane | Checking values while you learn |
textContent | An element on the page | What the reader should see |
alert | A blocking dialog | A short pause, not everyday UI |
Click Try it in JavaScript under an example. That opens /javascript/try. The page is on the right. The console is under it.
console.log
console.log prints a value in the console. The page does not change. You can log a string, a number, or several values in one call.
Example
console.log("Hello from the console.");
console.log(2 + 2);
let score = 10;
console.log("score is", score);This is the fastest way to see what a name holds. Keep it while you debug. Remove it when the page already shows the result.
Write on the page
Find an element, then set textContent. The reader sees the new words. PrefertextContent for plain text. It does not parse tags.
Example
<p id="out">Waiting.</p>
<script>
const out = document.getElementById("out");
out.textContent = "The page just changed.";
console.log("The console can still log too.");
</script>document.body.textContent = "..." replaces the whole body. Use an id when you want to keep the rest of the page.
alert
alert opens a dialog and waits until the user clicks OK. Nothing else on that page runs until the dialog closes. That makes it a poor default for output.
Example
alert("This stops the page until you click OK.");
console.log("This line runs after the alert closes.");Use it once to prove a script ran. Then switch to the console or the page. Stacked alerts are hard to dismiss and hide the result you actually care about.
innerHTML is not the first tool
innerHTML writes markup into an element. The browser parses tags. That is useful later. For a beginner string, textContent is enough and safer.
Example
<p id="out"></p>
<script>
const out = document.getElementById("out");
out.textContent = "Plain text. Tags stay as words: <b>hi</b>";
</script>Do not put untrusted text into innerHTML. For words you control, textContent is the default in this tutorial.
Skip document.write
Older examples call document.write. If you run it after the page has loaded, it can wipe the document. Do not use it in new code. Use textContent or the console instead.
A small habit
Log while you figure out a value. Write on the page when the reader should see it. Avoid alertexcept as a one-off check.
Next: statements — the lines that run in order, each ended with a semicolon.