Learn JavaScript · lesson 23 of 60 · about 8 minutes
Block Scope
Find the longest word in the visitor's comment: learn where let and const are visible, and keep a value alive across a loop by declaring it outside.
What you'll learn
- Explain block scope
- Recognise ReferenceError
- Avoid var surprises
The longest word
Under the word count, Sam wants to show the longest word in the visitor's comment. The program walks the comment a character at a time, building the current word and remembering the longest so far. Those two variables have to outlive every lap, so where you declare them matters: that's block scope.
Variables live inside their braces
A variable made with let or const only exists inside the { } block where it was created. That's called block scope. Outside the block, using it causes a ReferenceError.
To use a value after a block, declare the variable before the block.
Inside and outside
let message = "outside";
if (true) {
const secret = "inside";
message = secret;
}
console.log(message);
try {
console.log(secret);
} catch (e) {
console.log(e.name);
}Output
inside
ReferenceErrorWhy not var?
Older code uses var, which ignores block scope and can be used before its line runs (giving undefined). That causes confusing bugs, so modern JavaScript uses let and const.
var leaks out of blocks
for (var i = 0; i < 3; i++) {}
console.log(i);
for (let j = 0; j < 3; j++) {}
console.log(typeof j);Output
3
undefinedFinding the longest word
const commentText = "Great post, thanks Sam!";
// the longest word in the visitor's comment
let longest = "";
let current = "";
for (let i = 0; i < commentText.length; i++) {
if (commentText[i] === " ") {
current = "";
} else {
current += commentText[i];
if (current.length > longest.length) {
longest = current;
}
}
}
document.querySelector("#longest").textContent = longest ? `Longest word: ${longest}` : "No words yet";
Tip
Declare a variable in the smallest block that needs it. current and longest are used across laps, so they go before the loop; anything only one lap needs can live inside it.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.