Arrays
An array is a list of values, written inside square brackets and separated by commas.
let answers
↑
a variable that holds the list
[ ]
↑
square brackets — this is an array
'Yes', 'No', 'Maybe'
↑
items, separated by commas
In practice, a list looks like this:
let answers = ['Yes', 'No', 'Maybe'];
Every item in an array has a position, called its index. Counting starts at 0, not 1.
let colors = ['red', 'yellow', 'blue', 'green'];
| Index | colors[index] |
|---|---|
0 | colors[0] → "red" |
1 | colors[1] → "yellow" |
2 | colors[2] → "blue" |
3 | colors[3] → "green" |
Finding elements
To find an element on the page and control it, we use querySelector. We need to find two elements — the ball itself, so we know when it's clicked, and the answer paragraph inside it, so we can change its text.
document.querySelector("button")
↑
finds the outer ball, so we can listen for clicks
document.querySelector("p")
↑
finds the inner circle, so we can change its text
Picking a random answer
To pick a random item from the array, we use Math.random() to get a random index.
Math.random()
↑
random decimal between 0 and 1
answers.length
↑
how many items are in the array
Math.floor(...)
↑
rounds down to a whole number, so we get a valid index
Practice before we build
Get started
Let's practice in the browser before we build the real thing.
Go to your game, then press F12 to open the
console. Then, in your script.js file, do the
exercises below. When you're finished we can unlock the JS file.
Example array
let names = ['Sadie', 'Dasie', 'Bob', 'Josie'];
Try it yourself
1. Write a list of animals
let animals = []; // add animals inside the brackets — remember the quotation marks!
console.log(animals);
2. Write a list of games
let games = []; // add games inside the brackets — remember the quotation marks!
console.log(games);
3. Write a list of colors, using the variable name colors
// define the variable and make a list
console.log(colors);
4. Currently this logs the second item in the list. Change it to log the first item instead.
let sports = ['soccer', 'football', 'dance', 'cross country'];
console.log(sports[1]); // change this
5. Log how many items are in the list
let sports = ['soccer', 'football', 'dance', 'cross country'];
console.log(sports.length);
Build the game
Here's the finished game. Open the Preview tab and click the ball — it's fully working now. Add everything in green — check all three tabs.
Ask Arissa for the password after you tried yourself.
Ask Arissa for the password after you tried yourself.
Ask Arissa for the password after you tried yourself.