Ad – 728Γ—90
🌱 Beginner

Hello World in JavaScript – Writing Your First Program

Every programming journey begins with the same milestone: making the computer say "Hello, World!" In JavaScript, you have multiple ways to do this β€” and each one teaches you something different about how JS interacts with browsers and terminals. This lesson covers console.log(), alert(), document.write(), template literals, and the errors you're almost certain to run into as a beginner.

⏱️ 18 min read 🎯 Beginner πŸ“… Updated 2026

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.

JavaScript
console.log("Hello, World!");
console.log("My name is JavaScript");
console.log(42);
console.log(true);
console.log("The answer is", 42);
β–Ά Output
Hello, World! My name is JavaScript 42 true 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:

JavaScript
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.

JavaScript
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() Only Works in Browsers

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.

Ad – 336Γ—280

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.

JavaScript
// 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:

MethodWhere Output AppearsBlocks Execution?Use in Production?
console.log()DevTools console / terminalNoYes (debugging)
alert()Browser popup dialogYesRarely
document.write()HTML page bodyNoNo (obsolete)
innerHTMLA specific HTML elementNoYes
textContentA specific HTML element (text only)NoYes (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.

JavaScript
<!-- ❌ 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>
πŸ’‘
Best Practice: Use defer

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:

JavaScript
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);
β–Ά Output
Hello, Alice Smith! Hello, Alice Smith! Welcome to ylearner, Alice!

Common Beginner Errors

Every beginner makes these mistakes. Knowing them in advance saves hours of frustration:

JavaScript
// 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!)
β–Ά Common error messages
TypeError: name is not a function ReferenceError: Cannot access 'age' before initialization TypeError: console.Log is not a function SyntaxError: Unterminated string literal Age: 205
ℹ️
JavaScript is Case-Sensitive

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

  1. Open your browser console (F12) and use console.log() to print your name, your age, and true.
  2. Try console.warn("Watch out!") and console.error("Oops!") β€” notice the different styling.
  3. Use string concatenation with + to print "Hello, [your name]! You are [age] years old."
  4. Rewrite the same message using a template literal (backticks and ${}).
  5. Intentionally create a ReferenceError by 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 TypeError or ReferenceError.

Interview Questions

  • What is the difference between console.log() and alert()?
  • 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 ReferenceError mean in JavaScript?
  • What is the difference between placing a script tag in <head> with defer versus placing it before </body>?

Frequently Asked Questions

Why does console.log() show "undefined" after my output? +

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.

Can I use console.log() in production code? +

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.

What's the difference between single quotes, double quotes, and backticks? +

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.

Why does "Age: " + 20 + 5 give "Age: 205" instead of "Age: 25"? +

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).

How do I print an object nicely in the console? +

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.