β‘ 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,
deferattribute)
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.
Next up: the browser console, your essential tool for testing and debugging throughout this 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 parsing the HTML, runs the JavaScript code inside, and then carries on with the rest of the page. 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
.jsfile 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 asrcattribute, 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
(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. Deferred scripts also run in the order they appear in the HTML. Note that defer only works on external scripts (ones with a src); on an inline script it's ignored.
π‘ 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.
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:
- Create a new project folder called
js-practice - Inside it, create two files:
index.htmlandapp.js - 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>
- 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"]);
- Open
index.htmlin your browser (using Live Server, or just double-click the file) - Open the Console (F12 β Console tab)
- 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?
Question 4: What happens with this code?
<script src="app.js">
console.log("Hi!");
</script>
Question 5: Which of these is a good JavaScript comment?
π Learning Journal
Take five minutes to add to your learning journal. Write down:
- Key concepts you learned
- What clicked β the idea or technique that made sense
- Questions or confusion, so you know what to revisit
- Ideas to try on your own pages
- How you feel about your progress
βοΈ This lesson's prompt: Imagine a script in the <head> (without defer) tries to find your page's <h1>. Explain in your own words what goes wrong, and describe two different ways to fix it. Which approach will you use on your own site, and why? What's still unclear about when scripts run?
Summary
π Key Takeaways
- Add JavaScript with the
<script>tag β either inline or linked viasrc - External scripts (separate
.jsfiles) are the professional standard - Place scripts before
</body>or usedeferin 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!
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.
π‘ When to Comment
Comment to explain why, not what. Good code is mostly self-explanatory. Use comments for non-obvious decisions, workarounds, or TODOs.