Skip to main content

⚡ Lesson 2: Linking Scripts & the Console

Connect JavaScript to your HTML pages and start writing real code using the browser console and external script files.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Add JavaScript to an HTML page using the <script> tag
  • Understand the difference between inline scripts and external script files
  • Use console.log() to output messages to the browser console
  • Open and use the DevTools Console for testing and debugging
  • Explain why script placement matters (head vs. body, defer attribute)

Estimated Time: 40 minutes

Project: Create an HTML page linked to an external JavaScript file

📑 In This Lesson

Introduction

In the previous lesson, you learned what JavaScript is. Now it's time to learn how to actually get JavaScript running on a page. There are two ways to include JavaScript in an HTML document: writing it directly inside the HTML (inline) or linking to a separate .js file (external). Both use the <script> tag.

You'll also meet your new best friend: the browser console. The console is where you'll test code, see output, and debug problems throughout this entire course.

Inline Scripts

The simplest way to add JavaScript to an HTML page is to write it directly inside a <script> tag. This is called an inline script.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First JS Page</title>
</head>
<body>
    <h1>Hello!</h1>
    <p>Check the console for a message.</p>

    <script>
        console.log("Hello from JavaScript!");
    </script>
</body>
</html>
                

When the browser reaches the <script> tag, it pauses rendering, executes the JavaScript code inside, and then continues. The message "Hello from JavaScript!" appears in the browser's console (not on the page itself).

⚠️ When to Use Inline Scripts

Inline scripts are fine for quick tests and tiny snippets, but for real projects you should use external files. Inline scripts mix behavior (JS) with structure (HTML), making your code harder to maintain. Think of it like inline CSS vs. a stylesheet.

External Script Files

The professional approach is to write JavaScript in a separate .js file and link it with the src attribute on a <script> tag. This is exactly like how you link CSS with a <link> tag.

The HTML file (index.html)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>External Script Demo</title>
</head>
<body>
    <h1>My Page</h1>

    <script src="app.js"></script>
</body>
</html>
                

The JavaScript file (app.js)


// app.js — your first external script
console.log("This message comes from app.js!");
console.log("The script is linked and running.");
                

✅ Benefits of External Scripts

  • Separation of concerns — HTML stays clean, JS lives in its own file
  • Reusability — the same .js file can be linked from multiple pages
  • Caching — browsers cache external files, so returning visitors load pages faster
  • Easier debugging — errors point to a specific file and line number
⚠️ Important: When a <script> tag has a src attribute, any code inside the tag is ignored. Don't mix them — use one or the other.

<!-- ❌ BAD — the inline code is ignored when src is present -->
<script src="app.js">
    console.log("This will NOT run!");
</script>

<!-- ✅ GOOD — use separate tags -->
<script src="app.js"></script>
<script>
    console.log("This WILL run.");
</script>
                

Script Placement & Loading

Where you place the <script> tag matters. When the browser encounters a script, it stops parsing the HTML to download and execute it. This can cause problems if your script tries to access HTML elements that haven't been created yet.

Three Common Approaches

graph TD A["Option 1: Script in <head>
(blocks page rendering)"] --> D["❌ Elements don't exist yet"] B["Option 2: Script before </body>
(safe — HTML is parsed first)"] --> E["✅ All elements exist"] C["Option 3: Script in <head> with defer
(modern best practice)"] --> F["✅ Downloads in parallel,
runs after HTML is parsed"] style A fill:#fef2f2,stroke:#ef4444,stroke-width:2px,color:#1e293b style B fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style C fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b

Option 1: Script in the <head> (Risky)


<head>
    <script src="app.js"></script>
</head>
<body>
    <h1 id="title">Hello</h1>
</body>
                

Problem: app.js runs before the <h1> exists. If your script tries to find that element, it will get null.

Option 2: Script Before </body> (Safe)


<body>
    <h1 id="title">Hello</h1>

    <script src="app.js"></script>
</body>
                

The HTML is fully parsed before the script runs. This is the traditional safe approach.

Option 3: defer Attribute (Modern Best Practice)


<head>
    <script src="app.js" defer></script>
</head>
                

The defer attribute tells the browser: "Download this script in the background, but don't run it until the HTML is fully parsed." This gives you the best of both worlds — the script is in the <head> (clean structure) but runs after the page is ready.

💡 Our Approach in This Course

We'll primarily use Option 2 (script before </body>) because it's the most explicit and easiest to understand. As you get comfortable, you can switch to defer. Both are correct.

The Browser Console

The console is a panel in your browser's Developer Tools where JavaScript output appears. It's also where you can type JavaScript commands and run them instantly. You'll use it constantly.

How to Open the Console

Browser Shortcut (Windows/Linux) Shortcut (Mac)
Chrome Ctrl + Shift + J Cmd + Option + J
Firefox Ctrl + Shift + K Cmd + Option + K
Edge Ctrl + Shift + J Cmd + Option + J
Any Browser F12 then click the Console tab

Once open, you can type any JavaScript directly into the console and press Enter to run it. Try these:


2 + 2
"Hello" + " " + "World"
Math.random()
                

Output:

4
"Hello World"
0.7423189156482... (random number between 0 and 1)
                    

The console is your JavaScript playground. Any time you want to test a quick idea, try it in the console first.

Console Methods

console.log() is the most common way to output information, but the console object has several other useful methods:


// Standard output
console.log("Regular message");

// Informational (often styled with a blue icon)
console.info("This is informational");

// Warning (yellow background / icon)
console.warn("This is a warning!");

// Error (red background / icon)
console.error("Something went wrong!");

// Table format (great for arrays and objects)
console.table(["apple", "banana", "cherry"]);

// Grouping related messages
console.group("My Group");
console.log("Message 1");
console.log("Message 2");
console.groupEnd();

// Timing how long something takes
console.time("timer");
// ... some code ...
console.timeEnd("timer");
                

✅ Pro Tip: console.log() is Your #1 Debugging Tool

When your code isn't working as expected, sprinkling console.log() statements throughout your code is the quickest way to understand what's happening. Print variable values, check which branches of code execute, and verify data formats. You'll use this technique constantly.

⚠️ Console Output ≠ Page Output

console.log() prints to the DevTools Console, not to the web page itself. Users visiting your site won't see console messages unless they open DevTools. To display something on the page, you'll learn to manipulate the DOM in Module 4.

JavaScript Comments

Comments are notes in your code that the browser ignores. They're for humans — to explain what your code does, leave reminders, or temporarily disable code.


// This is a single-line comment
// Everything after // on this line is ignored

console.log("This runs"); // Comments can go after code too

/*
  This is a multi-line comment.
  It can span as many lines as you need.
  Great for longer explanations.
*/

/* You can also use multi-line syntax on one line */
                

💡 When to Comment

Comment to explain why, not what. Good code is mostly self-explanatory. Use comments for non-obvious decisions, workarounds, or TODOs.


// ❌ Bad comment — just restates the code
let age = 25; // set age to 25

// ✅ Good comment — explains WHY
let age = 25; // Default age for demo accounts (per product spec)
                

Hands-on Exercise

🏋️ Exercise: Your First JS Project

Objective: Create an HTML page linked to an external JavaScript file and verify it works using the console.

Instructions:

  1. Create a new project folder called js-practice
  2. Inside it, create two files: index.html and app.js
  3. Write the HTML below in index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Practice</title>
</head>
<body>
    <h1>JavaScript Practice</h1>
    <p>Open the console to see messages.</p>

    <script src="app.js"></script>
</body>
</html>
                    
  1. Write the following in app.js:

// My first external JavaScript file!
console.log("app.js is connected and running!");

// Experiment with different console methods
console.log("Regular log message");
console.warn("This is a warning");
console.error("This is an error (not a real one!)");
console.info("Here's some info");

// Try some math
console.log("5 + 3 =", 5 + 3);
console.log("10 * 4 =", 10 * 4);

// Try a table
console.table(["HTML", "CSS", "JavaScript"]);
                    
  1. Open index.html in your browser (using Live Server or double-click)
  2. Open the Console (F12 → Console tab)
  3. Verify you see all the messages
💡 Hint

If you see nothing in the console, check that app.js is in the same folder as index.html. Also check for typos in the filename — src="app.js" must match the actual file name exactly (case-sensitive on some systems).

✅ What You Should See

The console should display: a regular log message, a yellow warning, a red error message, an info message, two math results (8 and 40), and a table with three rows showing HTML, CSS, and JavaScript. If you see all of these, your external script is linked correctly!

🎯 Quick Quiz

Question 1: Where is the recommended place to put a <script> tag that links to an external file?

Question 2: What does console.log() do?

Question 3: What does the defer attribute do on a <script> tag?

Summary

🎉 Key Takeaways

  • Add JavaScript with the <script> tag — either inline or linked via src
  • External scripts (separate .js files) are the professional standard
  • Place scripts before </body> or use defer in the <head>
  • console.log() prints to the DevTools Console — your #1 debugging tool
  • Other console methods: .warn(), .error(), .table(), .group()
  • Comments (// and /* */) explain your code for humans

📚 Additional Resources

🚀 What's Next?

Now that you can run JavaScript, it's time to learn the building blocks of the language. In the next lesson, you'll learn about variables and data types — how to store and work with information in JavaScript.

🎉 Congratulations!

You've completed Lesson 2. You can now link JavaScript to HTML and use the console. You're writing real code!