console.log() β The Developer's Best Friend
console.log() is by far the most important output method in JavaScript. It writes to the browser's DevTools console or the terminal (in Node.js). Unlike alert(), it doesn't interrupt the user β making it the standard tool for debugging and learning.
console.log("Hello, World!");
console.log("My name is JavaScript");
console.log(42);
console.log(true);
console.log("The answer is", 42);
Notice that console.log() can accept multiple arguments separated by commas β it prints them all on one line with a space between them. This is extremely handy for debugging.
Other console Methods
The console object has several other useful methods:
console.log("This is a regular log");
console.warn("This is a warning!"); // Yellow in DevTools
console.error("Something went wrong!"); // Red in DevTools
console.info("Informational message"); // Blue icon in some browsers
console.table([1, 2, 3]); // Renders data as a table
console.clear(); // Clears the console
alert() β Browser Popup Dialogs
alert() shows a popup dialog box in the browser. It pauses all JavaScript execution until the user clicks "OK". While useful for quick demos, it's almost never used in real websites because it creates a poor user experience.
alert("Hello, World!");
alert("This pauses ALL JavaScript execution until you click OK.");
// alert always converts its argument to a string
alert(42); // Shows "42"
alert(true); // Shows "true"
alert() is a browser-only function (part of the window object). If you run code with alert() in Node.js, you'll get a ReferenceError: alert is not defined error.
document.write() β Writing to the Page
document.write() inserts HTML directly into the page as it loads. It's mostly obsolete in modern development β if called after the page has loaded, it overwrites the entire document. You may see it in older tutorials, but avoid it in real projects.
// Only use during page load β calling after load destroys the page!
document.write("<h1>Hello, World!</h1>");
document.write("<p>Written by JavaScript</p>");
Output Methods Comparison
Here's a quick reference to help you choose the right output method:
| Method | Where Output Appears | Blocks Execution? | Use in Production? |
|---|---|---|---|
console.log() | DevTools console / terminal | No | Yes (debugging) |
alert() | Browser popup dialog | Yes | Rarely |
document.write() | HTML page body | No | No (obsolete) |
innerHTML | A specific HTML element | No | Yes |
textContent | A specific HTML element (text only) | No | Yes (preferred) |
The Script Tag β head vs body vs defer
JavaScript is included in HTML using the <script> tag. Where you place it matters significantly β it affects when the script runs relative to the HTML being parsed.
<!-- β In <head> without defer: runs before HTML exists -->
<head>
<script src="app.js"></script>
</head>
<!-- β
In <head> with defer: loads in parallel, runs after HTML -->
<head>
<script src="app.js" defer></script>
</head>
<!-- β
Before </body>: HTML is ready when script runs -->
<body>
<!-- page content -->
<script src="app.js"></script>
</body>
Using <script src="..." defer> in the <head> is the modern best practice. It starts downloading the script immediately (non-blocking) and runs it after the HTML is fully parsed, combining the benefits of both approaches.
String Concatenation
You can combine strings using the + operator. This is called string concatenation:
let firstName = "Alice";
let lastName = "Smith";
// Old way: string concatenation with +
console.log("Hello, " + firstName + " " + lastName + "!");
// Modern way: template literals (backticks)
console.log(`Hello, ${firstName} ${lastName}!`);
// Template literals can also span multiple lines
let message = `Welcome to ylearner,
${firstName}!`;
console.log(message);
Common Beginner Errors
Every beginner makes these mistakes. Knowing them in advance saves hours of frustration:
// Error 1: Calling something that isn't a function
let name = "Alice";
name(); // TypeError: name is not a function
// Error 2: Using a variable before declaring it (with let/const)
console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 25;
// Error 3: Typo in method name (case-sensitive!)
console.Log("Hello"); // TypeError: console.Log is not a function
Console.log("Hello"); // ReferenceError: Console is not defined
// Error 4: Missing closing quote
console.log("Hello, World!); // SyntaxError: Unterminated string literal
// Error 5: Adding a number to a string accidentally
console.log("Age: " + 20 + 5); // "Age: 205" (not 25!)
console.log, console.Log, and Console.log are three completely different things β and only the first one exists. JavaScript treats uppercase and lowercase letters as distinct in all identifiers and method names.
ποΈ Practical Exercise
- Open your browser console (F12) and use
console.log()to print your name, your age, andtrue. - Try
console.warn("Watch out!")andconsole.error("Oops!")β notice the different styling. - Use string concatenation with
+to print"Hello, [your name]! You are [age] years old." - Rewrite the same message using a template literal (backticks and
${}). - Intentionally create a
ReferenceErrorby calling a variable that doesn't exist. Read the error message carefully.
π₯ Challenge Exercise
Create an HTML file with a <p id="output"> element. Write an external app.js file (linked with defer) that sets the paragraph's textContent to a greeting using a template literal: include the current day of the week using new Date().toLocaleDateString('en-US', {weekday: 'long'}) and a hardcoded name of your choice.
π Summary
console.log()is the primary output method β use it for debugging and learning.alert()shows a browser popup but blocks execution; avoid it in real projects.document.write()is obsolete β it overwrites the page if called after load.- Use
<script defer>to load scripts in the<head>without blocking HTML parsing. - Template literals (backticks) are cleaner than
+concatenation for building strings. - JavaScript is case-sensitive β typos in method names cause
TypeErrororReferenceError.
Interview Questions
- What is the difference between
console.log()andalert()? - Why is
document.write()considered bad practice in modern JavaScript? - What is a template literal and what advantages does it have over string concatenation?
- What does
ReferenceErrormean in JavaScript? - What is the difference between placing a script tag in
<head>withdeferversus placing it before</body>?
Frequently Asked Questions
When you type console.log("Hello") in the browser REPL, you see Hello (the output) followed by undefined (the return value of console.log itself). The function prints its argument and returns undefined. This is normal and only appears in the interactive REPL.
Technically yes, but it's not recommended. Console logs expose information to anyone who opens DevTools, can slow down performance if overused, and clutter the console output. Most production build tools (like Webpack or Vite) can automatically strip console.log calls from production builds.
Single quotes (') and double quotes (") are interchangeable for regular strings. Backticks (`) create template literals that support embedded expressions (${variable}) and multi-line strings without escape characters. Most style guides pick one quote style (often single quotes) and stick with it consistently.
JavaScript evaluates expressions left to right. "Age: " + 20 first produces the string "Age: 20", then "Age: 20" + 5 continues string concatenation to give "Age: 205". Fix it by doing the math first: "Age: " + (20 + 5).
Use console.log() directly with the object β most browsers render it as an expandable tree. For a formatted JSON string, use console.log(JSON.stringify(obj, null, 2)). For tabular data, console.table(obj) renders it as a formatted table.