javascript · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every variable lives in a , and only that scope can see it.
A variable made with let or const lives inside the block where you made it: the nearest pair of curly brackets around it. That region is its scope. Code inside the block can use the name. Code outside cannot, and gets a ReferenceError.
Names made outside every block live in the , so every part of the program can see them. Blocks nest like boxes inside boxes: inner code can look outwards, never inwards.
If an inner block makes a variable with a name already used outside, that is . Inside the block the new one wins. Outside, the old one is untouched.
const shop = "Corner Café";
function openUp() {
const greeting = `Welcome to ${shop}`;
console.log(greeting);
}
openUp();
console.log(typeof greeting); typeof is the one safe way to ask about a name that does not exist here: it gives undefined instead of an error.
guess first
Two boxes called total. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let total = 10;
if (total > 5) {
let total = 99;
console.log(total);
}
console.log(total);
your turn
Your turn. Prove a variable stays inside its function.
Pick a price in pence for line 6. On line 7, type the name of the variable that only lives inside formatPrice, so typeof shows it is invisible out here.
fix it
The best score went missing. Can you fix it?
- Where is
bestmade, and where is it used? Are they in the same block? bestlives inside the loop's block, so line 6 cannot see it. It is also reset to 0 on every lap.- Move
let best = 0;above theforline, so it lives in the outer scope, then press run.
nailed it
you know where every name lives. :D
- A variable lives in the block where you make it.
- Inner code can see outwards, never inwards.
- Shadowing hides an outer name inside one block.
new words in your collection
- scope
- global scope
- shadowing
This lesson isn’t saved. A free account remembers every lesson you finish.