Global, function and block scope
typeof on a name that isn't visible gives "undefined" instead of throwing, which makes it handy for these experiments.
Scope is the region of code where a variable can be seen: global scope is visible everywhere, function scope inside one function, and block scope (for let and const) inside one pair of braces; lookups go from the inside outwards, and an inner variable with the same name shadows the outer one.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Predict what this prints, then check: let a = 1; { let a = 2; console.log(a); } console.log(a);
Rewrite this so i can't be read after the loop: for (var i = 0; i < 3; i++) {} console.log(i);
Write a function makeLabel(text) that uses a local prefix constant, and show that prefix is not visible outside it.
Explain it without notes
Name the kinds of scope in JavaScript and which declarations belong to each.
What is the scope chain, and what happens when a name isn't found?
What is lexical scope? Give an example where it matters.
What is shadowing, and how does it differ from reassigning an outer variable?
Console
(nothing was printed)Expected console output
Hectal JavaScript Scope
var ignores the block
undefined
undefined
undefined