Lesson 4 · Websites from scratch

JavaScript basics

Variables, functions and events, by building a dice roller.

About 25 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

HTML says what's on the page. CSS says how it looks. JavaScript makes it do things: respond to clicks, keep score, change the page while you watch. It's a real programming language, the only one every browser runs natively, and the same language runs on servers (with Node.js) and inside plenty of desktop and phone apps. Your code here runs right in the browser, on your device, so none of it needs an internet connection. In this lesson you'll learn the core pieces (variables, functions and events) and use them to build a dice roller.

Variables: named boxes for values

A variable stores a value under a name so you can use it later.

const player = 'Sam'   // a string (text), in quotes
let score = 0          // a number
let gameOver = false   // a boolean: true or false
  • const makes a variable you can't reassign. Use it by default.
  • let makes one you can change later, like a score.
  • (You'll see var in old code. It's the original way, with confusing rules. Skip it.)

Change a let with =. The right side is worked out first, then stored:

score = score + 10   // take score, add 10, store it back
score += 10          // shorter way to write the same thing

To glue values into text, use a template literal: backticks, with ${…} around anything you want filled in.

console.log(`${player} has ${score} points`)   // Sam has 20 points

console.log prints to the console, a panel for messages that developers use constantly to check what their code is doing.

Challenge

Keep score

score starts at 0. Add 10 to it twice (on two separate lines, before the console.log), then press Run and check the console says 20 points.

Console
  1. Nothing logged yet.
  • score ends up at 20
  • The console shows the 20 points
Question

Quick check

You write const lives = 3 and later lives = 2. What happens?
Pick an answer.

Functions: reusable chunks of code

A function is a named set of instructions you can run whenever you want. It can take parameters (inputs) and return a result.

function double(n) {
  return n * 2
}

double(4)    // 8
double(21)   // 42

n is the parameter. Calling double(4) runs the code with n set to 4, and return hands the answer back to whoever called it.

Making decisions with if

Programs need to choose. An if statement runs code only when a condition is true, and else covers the other case:

if (score >= 100) {
  console.log('New high score!')
} else {
  console.log('Keep going')
}

Conditions use comparison operators, which give back true or false:

OperatorMeansExample that's true
===is equal to3 === 3
!==is not equal to'cat' !== 'dog'
> <greater than, less than10 > 2
>= <=at least, at most6 <= 6
&&and: both must be truelives > 0 && !gameOver
||or: either can be truekey === 'w' || key === 'ArrowUp'
!not: flips true and false!gameOver

Use === (three equals) to compare. The two-equals version, ==, converts types before comparing, so '5' == 5 is true, which hides bugs. Remember that a single = doesn't compare anything: it assigns.

Random numbers

Math.random() gives you a random decimal from 0 up to (but never reaching) 1, like 0.3817…. To turn that into a dice roll from 1 to 6:

Math.random()                      // 0 to 0.999…
Math.random() * 6                  // 0 to 5.999…
Math.floor(Math.random() * 6)      // 0, 1, 2, 3, 4 or 5
Math.floor(Math.random() * 6) + 1  // 1, 2, 3, 4, 5 or 6

Math.floor chops off the decimal part (rounds down). The + 1 shifts the range up so you never roll a 0.

Question

Quick check

What can Math.floor(Math.random() * 10) give you?
Pick an answer.

Events: reacting to the user

The page is made of elements, and JavaScript can grab any of them with document.querySelector, using the same selectors as CSS:

const button = document.querySelector('#roll')
const result = document.querySelector('#result')

An event is something that happens: a click, a key press, the page loading. addEventListener says "when this event happens on this element, run this function". The function you hand over is called a callback: you don't call it yourself, the browser calls it back later, every time the event happens:

button.addEventListener('click', function () {
  result.textContent = 'You clicked!'
})

textContent is the text inside an element. Set it, and the page updates instantly. Notice the pattern, because almost every interactive page uses it: find the elements once at the top, listen for events, and in the callback update your variables and then the page.

Build it: a dice roller

Challenge

Roll the dice

  1. Finish rollDie so it returns a random whole number from 1 to 6.
  2. In the click handler, call rollDie() and show the number in the result paragraph.
  3. Press Run, then click Roll a few times.

Bonus: keep a let rolls = 0 counter and show how many times you've rolled, or show a die face (⚀ ⚁ ⚂ ⚃ ⚄ ⚅) next to the number.

Console
  1. Nothing logged yet.
  • rollDie returns whole numbers from 1 to 6, and can return both 1 and 6
  • Clicking Roll shows a number from 1 to 6 on the page
  • The number changes as you keep rolling

Recap

  • const for values that don't change, let for ones that do; strings, numbers and booleans are the basic types.
  • Functions bundle code you can reuse; parameters go in, return sends a result out.
  • Math.floor(Math.random() * 6) + 1 gives a whole number from 1 to 6.
  • document.querySelector grabs an element, addEventListener runs code when something happens, and textContent changes what it says.

Finished this lesson?

Mark it complete to track your progress on this device.