Your first script
Overview
Typing into the console is great for experiments, but anything you type there disappears when you reload the page. Real programs live in files. In this topic you’ll create an HTML page and a JavaScript file, connect the two, and learn how the browser decides when to run your code.
Create the files
In your course folder, create a file called index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first script</title>
<script src="app.js" defer></script>
</head>
<body>
<h1>Open the console</h1>
</body>
</html>Then create app.js next to it, in the same folder:
console.log('Hello from app.js!');Your folder should now look like this:
js-course/
├── index.html
└── app.jsRun it
Open index.html in your browser — double-click it, or drag it onto a browser window. Then open the console. You should see your message.
Now change the message in app.js, save, and reload the page. The new message appears. That edit → save → reload cycle is how you’ll work from now on.
Nothing printed? Check that both files are in the same folder and that the file name in
srcmatches exactly —App.jsandapp.jsare different files on most web servers. Also make sure you saved the file.
How the browser runs a script
When the browser loads a page, it reads (parses) the HTML from top to bottom. When it reaches a <script> tag, what happens next depends on where the tag is and which attributes it has:
- A plain
<script>in<head>stops the browser. It must download and run the script before it can carry on building the page. Worse, the script can’t see any elements below it, because they don’t exist yet. <script defer>downloads the file in the background while the page keeps parsing, then runs it once the whole page has been read. This is the best default.- A plain
<script>at the end of<body>also runs after the page content exists. It works, and you’ll see it in older code, but the download only starts late.
You can see the difference for yourself. Remove defer and try to read the heading:
// app.js — loaded in <head> WITHOUT defer
const heading = document.querySelector('h1');
console.log(heading); // null — the <h1> hasn't been parsed yetAdd defer back and the same code logs the <h1> element.
Inline scripts
You can also write JavaScript directly between script tags:
<script>
console.log('I live inside the HTML file');
</script>That is handy for a quick test, but separate files are easier to edit, reuse and cache, so this course uses them.
Using console.log
console.log() prints whatever you give it. It’s the simplest way to see what your program is doing:
console.log('Text'); // a string
console.log(42, true, null); // several values at once
console.log('Total:', 3 * 7); // a label and a valueThe console object has a few relatives that are useful later:
console.warn('Careful!'); // yellow warning
console.error('Broken!'); // red error with a stack trace
console.table([{ a: 1 }, { a: 2 }]); // data as a tableCommon beginner mistakes
- Opening the
.jsfile in the browser instead of the.htmlfile. The browser just shows the code as text; it only runs scripts that a page loads. - Forgetting to save before reloading. Turn on auto save in your editor.
- A wrong path, such as
src="js/app.js"when the file isn’t in ajsfolder. Paths are relative to the HTML file. - Smart quotes pasted from a document (
‘ ’) instead of straight quotes (' '). JavaScript only understands straight quotes.
Say hello by name
Change the script so it prints a greeting that includes your own name, then add a second line that prints how many letters your name has (hint — name.length).
const name = 'World';
console.log('Hello, ' + name + '!');const name = 'Asha';
console.log(`Hello, ${name}!`);
console.log(`Your name has ${name.length} letters.`);Summary
- Load a script with
<script src="app.js"></script>. - Put the script tag in
<head>withdefer, or at the end of<body>. console.log()prints values so you can see what your code is doing.- File names in
srcare case-sensitive and relative to the HTML file.