Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.4 — Scope
JavaScript · Example 1 of 3 ES2015+

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.

01

Predict what this prints, then check: let a = 1; { let a = 2; console.log(a); } console.log(a);

02

Rewrite this so i can't be read after the loop: for (var i = 0; i < 3; i++) {} console.log(i);

03

Write a function makeLabel(text) that uses a local prefix constant, and show that prefix is not visible outside it.

Explain it without notes

01

Name the kinds of scope in JavaScript and which declarations belong to each.

02

What is the scope chain, and what happens when a name isn't found?

03

What is lexical scope? Give an example where it matters.

04

What is shadowing, and how does it differ from reassigning an outer variable?

Global, function and block scope ES2015+

Console

(nothing was printed)

Expected console output

Hectal JavaScript Scope
var ignores the block
undefined
undefined
undefined