Your first script

Topic 3 of 4 in Getting started6 min readBeginnerFree course

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:

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:

JavaScript
console.log('Hello from app.js!');

Your folder should now look like this:

Text
js-course/
├── index.html
└── app.js

Run 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 src matches exactly — App.js and app.js are 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:

Three timelines. A plain script in the head stops HTML parsing while app.js downloads and runs. A defer script downloads in parallel and runs after parsing finishes. A script at the end of the body runs after parsing but only starts downloading late.

  • 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:

JavaScript
// app.js — loaded in <head> WITHOUT defer
const heading = document.querySelector('h1');
console.log(heading); // null — the <h1> hasn't been parsed yet

Add defer back and the same code logs the <h1> element.

Inline scripts

You can also write JavaScript directly between script tags:

HTML
<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:

JavaScript
console.log('Text');            // a string
console.log(42, true, null);    // several values at once
console.log('Total:', 3 * 7);   // a label and a value

The console object has a few relatives that are useful later:

JavaScript
console.warn('Careful!');   // yellow warning
console.error('Broken!');   // red error with a stack trace
console.table([{ a: 1 }, { a: 2 }]); // data as a table

Common beginner mistakes

  • Opening the .js file in the browser instead of the .html file. 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 a js folder. Paths are relative to the HTML file.
  • Smart quotes pasted from a document (‘ ’) instead of straight quotes (' '). JavaScript only understands straight quotes.
Exercise

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).

JavaScript
const name = 'World';
console.log('Hello, ' + name + '!');

Summary

  • Load a script with <script src="app.js"></script>.
  • Put the script tag in <head> with defer, or at the end of <body>.
  • console.log() prints values so you can see what your code is doing.
  • File names in src are case-sensitive and relative to the HTML file.