javascript · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An is a function written right where it is needed.
Naming a function you only hand over once is like labelling a sandwich you are about to eat. An arrow function skips the name: () => { }. The round brackets hold any parameters, then comes the arrow =>, then the block.
Write it straight inside addEventListener, and the listener sits right next to the button it belongs to.
A variable made outside the listener lives on between clicks. Each click can add one to count and show the new total, so the page remembers.
<button id="like">Like</button>
<p id="likes">0 likes</p> const button = document.querySelector("#like");
const likes = document.querySelector("#likes");
let count = 0;
button.addEventListener("click", () => {
count++;
likes.textContent = `${count} likes`;
}); Press run it to bring the page to life.
console
nothing logged yet
Use let for the count, because it changes. const would crash with a TypeError on the first click.
guess first
Three clicks. What does the jar say?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<button id="add">Add sweets</button>
<p id="jar">Jar: 10 sweets</p> const jar = document.querySelector("#jar");
let sweets = 10;
document.querySelector("#add").addEventListener("click", () => {
sweets = sweets + 2;
jar.textContent = `Jar: ${sweets} sweets`;
});
your turn
Your turn. Build a step counter.
Choose how many steps each click adds, then type the variable that holds the total. Press run and click a few times.
the page your code works on
<button id="step">Take a step</button>
<p id="steps">0 steps</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the counter has gone upnot checked yet
fix it
Scoring a goal crashes with a TypeError. Fix it!
the page your code works on
<button id="goal">Goal!</button>
<p id="score">Score: 0</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- two goals show Score: 2not checked yet
- The crash only happens on a click. Which line changes a value?
scoregoes up on every click, but it was made with a keyword that never allows changes.- Change const score to let score on line 2, then press run and click.
nailed it
your page can count now. :D
- An arrow function
() => { }is a function with no name. - Write it right inside
addEventListener. - A
letoutside the listener remembers between clicks.
new words in your collection
- arrow function
This lesson isn’t saved. A free account remembers every lesson you finish.