Free preview
Running JavaScript in a web page
Practical task · 15 min
The console is great for experiments, but real programs live in files. In this lesson you set up a small project where an HTML page loads a JavaScript file.
Project setup
- 1
Create a folder
Make a folder called
js-practiceand open it in VS Code. - 2
Create index.html
Type
!and press Tab to get the HTML skeleton, then add a heading. - 3
Create script.js
Add a file called
script.jsnext to it. - 4
Link the script
Add a script tag in the
<head>with thedeferattribute, as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript practice</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>JavaScript practice</h1>
</body>
</html>console.log("script.js is connected!");
alert("Hello!");Open index.html in the browser (or with the Live Server extension). You should see the alert box, and after closing it, the message in the console.
Why defer?
The browser reads HTML from top to bottom. A plain <script> in the <head> runs before the body exists, so code that tries to change the page finds nothing. `defer` tells the browser to download the script straight away but run it only after the whole page has been read. Always use it for scripts in the head. (Older tutorials put scripts at the end of the body instead, which works too.)
Output you'll use
| Tool | What it does | When to use it |
|---|---|---|
console.log(value) | Prints to the console | Checking values while you work: you'll use it constantly |
console.error(value) | Prints in red | Reporting problems |
alert(message) | Pops up a box | Quick tests only; real sites rarely use it |
prompt(question) | Asks the user to type something | Quick tests only |
Comments
// A single-line comment
/* A comment that can
span several lines */Use comments to explain why your code does something, not what it does. Good names usually explain the what.
Reading an error
Change console.log to console.lgo and reload. The console shows something like:
Uncaught TypeError: console.lgo is not a function script.js:1It tells you the kind of error, a message, and the file and line. Click the file name to jump straight to the problem. Fix it and reload.
Try it
Greeting with input
In script.js, use prompt to ask for the visitor's name, then log a greeting that includes it.
Show a hint
prompt returns whatever the person typed, so you can store it: const name = prompt("…").
Show a worked answer
const name = prompt("What's your name?");
console.log("Welcome, " + name + "!");Like this lesson?
JavaScript Programming has 22 lessons with exercises, quizzes and a final project.