All tutorials
Advanced

Scope

Where variables are visible: global, function, block.

1. Explanation

Scope determines where a variable can be accessed. Global scope = anywhere. Function scope = inside the function. Block scope = inside { } (only for let/const). Inner scopes can read outer variables (closure), but outer scopes cannot read inner ones.

2. Example

Try it yourself
Console
Click Run to see output.

3. Expected output

output
I'm everywhere inside outer inside block

4. Common mistakes

  • Polluting the global scope by forgetting let/const
  • Expecting var to be block-scoped — it isn't
  • Shadowing a variable accidentally with the same name in an inner scope

5. Practice questions

  1. Demonstrate block scope by declaring 'let x' inside an if-block
  2. Show how var leaks out of a for-loop but let doesn't
  3. Write a function that captures an outer variable
→ Try more practice problems