JavaScript Hello World

Write and run your first JavaScript program. Learn console.log, script tags, external JS files, and how to display output in the browser.

Beginner 5 min read 6 examples

console.log()

console.log() is JavaScript's primary output function. It prints values to the developer console - open it with F12 in Chrome, then click the Console tab.

JavaScript
console.log("Hello, World!");           // string
console.log(42);                        // number
console.log(true);                      // boolean
console.log([1, 2, 3]);                 // array
console.log({ name: "Alice", age: 30 });// object

// Multiple values in one call
console.log("Name:", "Alice", "| Age:", 30);
Hello, World! 42 true [1, 2, 3] {name: 'Alice', age: 30} Name: Alice | Age: 30
Template Literals for Cleaner Output

Use backtick template literals to embed variables directly in strings - much cleaner than concatenation with +:

JavaScript
const name = "Alice";
const age = 30;

// Old way (concatenation)
console.log("Name: " + name + ", Age: " + age);

// Modern way (template literal)
console.log(`Name: ${name}, Age: ${age}`);

Inline Script Tags

You can write JavaScript directly inside an HTML file using <script> tags. This is fine for small scripts and learning:

HTML index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello JS</title>
</head>
<body>
    <h1 id="output">Waiting...</h1>

    <script>
        const message = "Hello, World!";
        console.log(message);
        document.getElementById("output").textContent = message;
    </script>
</body>
</html>
Page shows: Hello, World! Console: Hello, World!

External JS Files (Best Practice)

For real projects, keep JavaScript in a separate .js file. Link it in HTML using the src attribute. Always use defer so the script loads after the HTML is parsed:

HTML index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My App</title>
    <!-- defer: load JS after HTML is parsed -->
    <script src="app.js" defer></script>
</head>
<body>
    <p id="greeting"></p>
</body>
</html>
JavaScript app.js
'use strict';

const hour = new Date().getHours();
let greeting;

if (hour < 12) {
    greeting = "Good morning!";
} else if (hour < 18) {
    greeting = "Good afternoon!";
} else {
    greeting = "Good evening!";
}

document.getElementById("greeting").textContent = greeting;
AttributeBehaviorUse When
(none)Blocks HTML parsing, executes immediatelyAvoid
deferDownloads in parallel, executes after HTML parsed, in orderMost scripts
asyncDownloads in parallel, executes immediately when readyIndependent scripts (analytics)
type="module"ES module - deferred by default, has own scopeModern JS with import/export

Run with Node.js

To run JavaScript outside the browser, save it as a .js file and run it with Node.js from the terminal:

JavaScript hello.js
const name = "Developer";
const version = process.version; // Node.js version

console.log(`Hello, ${name}!`);
console.log(`Running Node.js ${version}`);
Bash Terminal
node hello.js
Hello, Developer! Running Node.js v20.11.0

Console Methods

The console object has more than just log():

JavaScript
console.log("Standard output");
console.info("Informational message");
console.warn("Warning - something might be wrong");
console.error("Error occurred!");

// Print arrays/objects as a table
const users = [
    { name: "Alice", role: "admin" },
    { name: "Bob",   role: "editor" },
];
console.table(users);

// Group related logs
console.group("User Details");
console.log("Name: Alice");
console.log("Role: Admin");
console.groupEnd();

// Measure execution time
console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop"); // loop: 2.31ms

Output to the DOM

To show output on the actual webpage (not just the console), update the DOM:

JavaScript
// Get an element and set its text
document.getElementById("output").textContent = "Hello from JS!";

// Set HTML (careful with user input - XSS risk)
document.getElementById("output").innerHTML = "<strong>Bold text</strong>";

// Create and append a new element
const para = document.createElement("p");
para.textContent = "Dynamically added paragraph";
document.body.appendChild(para);
Avoid document.write()

document.write() is an old method that overwrites the entire page if called after loading. Never use it in modern JavaScript. Use element.textContent or DOM manipulation instead.

Frequently Asked Questions

console.log() prints values to the browser developer console (F12) or terminal (Node.js). It is the primary debugging tool in JavaScript - use it to inspect variable values, trace execution flow, and verify logic. It accepts any number of arguments and can print strings, numbers, objects, and arrays.

defer downloads the script in parallel with HTML parsing, then executes it after the HTML is fully parsed - in order. async downloads and executes as soon as ready, interrupting HTML parsing. Use defer for most scripts (preserves order). Use async only for independent scripts like analytics.

No - only use alert() for quick testing. It blocks the page and annoys users. For real output, use console.log() during development, or update the DOM (element.textContent, innerHTML) to show output on the page.

Best practice: put <script src="app.js" defer></script> in the <head> with the defer attribute. defer makes it load after HTML parsing without blocking. Old tutorials put scripts at the bottom of <body> - that works too but defer is the modern approach.