FunctionsExtra· 25 min read

Scope

Where variables live and who can see them — the key to avoiding mysterious bugs.

What you will learn

  • Tell global and local scope apart
  • Understand block scope with let/const
  • Avoid common scope mistakes

Global vs local

A variable declared inside a function is local — only that function can see it. A variable declared outside is global — everyone can see it.

Local variables stay inside their function
<script>
  let team = "CodingClave";   // global

  function show() {
    let role = "Trainer";      // local to show()
    document.write(team + " — " + role);
  }
  show();
  // document.write(role);  // would ERROR: role is not visible here
</script>
Live preview

team is declared outside any function, so it is global — code anywhere, including inside show(), can read it. role is declared inside show(), so it is local — it exists only while show() runs. That is why the commented-out last line would error: outside the function, role simply does not exist.

Note: Output: CodingClave — Trainer

Note: let and const are also block-scoped — a variable made inside { } (like an if or loop) only exists inside those braces. This prevents many accidental bugs.

Tip: Keep variables as local as possible. Fewer globals means fewer surprises and clashes — a habit of clean, bug-free code.

Q. A variable declared inside a function is:

Answer: Variables declared inside a function are local — only accessible within that function.

✍️ Practice

  1. Create a local variable in a function and confirm it cannot be read outside.
  2. Show that a let inside an if block is not visible outside it.

🏠 Homework

  1. Write a short note explaining global vs local scope with your own example.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →