JavaScript Scope & Hoisting

Where variables are visible.

✍️ 3 exercises + code challenge in this lesson

Scope decides where a variable can be used.

  • Global scope: declared outside any function or block; visible everywhere.
  • Function scope: declared inside a function; visible only inside it.
  • Block scope: let and const inside { } are visible only in that block.

Hoisting

Function declarations are "hoisted", so they can be called before they appear in the code. let and const cannot be used before their declaration (the "temporal dead zone").

Key Takeaways: JavaScript Scope & Hoisting

Mastering JavaScript Scope & Hoisting helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Scope & Hoisting Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
const site = "CodesInTech";   // global

function show() {
  const inside = "function scope";
  log(site, "|", inside);
}
show();

if (true) {
  let blockVar = "block scope";
  log(blockVar);
}
log(typeof blockVar); // undefined outside the block

log(hoisted()); // works: declarations are hoisted
function hoisted() { return "I was called before my definition"; }
</script>
Free sign-in required · Google login available

JavaScript Scope & Hoisting Practice Exercises

Check what you learned in “JavaScript Scope & Hoisting”.

/ 3 solved
Fill in the blank

Declare a block-scoped variable.

if (true) {
   x = 5;
}
✓ Correct! Not quite. Try again.
Multiple choice

Can a let variable declared inside { } be used outside the block?

✓ Correct! Not quite. Try again.
Code challenge

Inside the function, create a local variable message = "local" and log it.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services