Open original
Info
Demo 3.1

Adding JavaScript to a file using the <script> element

Files in this demo

├─ index.html
└─ script.js

JavaScript is the third language of the web. HTML is the content, CSS is the look, and JavaScript is the behaviour ~ anything that reacts, changes, or calculates.

You attach it with <script>, and there are two ways.

A separate file

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

This is what you want. Your JavaScript lives in its own file, and every page can share it.

Straight into the page

<script>
	console.log("hi");
</script>

Handy for a quick test. Fine to start with.

Where the tag goes matters

Put <script> at the bottom of the <body>, just before </body>.

If it goes in the <head>, the script runs before the page’s HTML exists ~ so any attempt to find an element on the page comes back empty and you get an error. It is a genuinely confusing bug the first time.

(The other fix is <script src="script.js" defer></script> in the head, which tells the browser to wait. Either is fine. Bottom of the body is easier to remember.)

The console

Open the console panel at the bottom right. console.log() prints to it, and it’s where errors show up. It’s the single most useful tool you have while learning ~ keep it open.

Next demoDefining variables with <code>let</code> and <code>const</code>
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console