SA-21/06, C-11, Asapur, Varanasi, UP support@kamaldnp.com +91 8318013442
JavaScript
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10
Try this code live
Lesson 11 of 35

JavaScript Scope — Global, Local & Block Scope Explained

5 min read · Free · No login needed

Scope is the answer to one simple question: where in your code can a variable be seen? A variable declared inside a function can only be used inside that function. A variable declared outside all functions can be used anywhere. Think of a village and a house: something announced in the village square (global) is known to everyone, but something said inside one house (local) is heard only by the people in that house.

Diagram — see how it fits together
Diagram: JavaScript Scope

Scope matters because it stops your code from stepping on itself. Two functions can both use a variable called total without clashing — as long as each total is local to its own function. Without scope, every name would be global, and a big program would be a mess of accidental overwrites.

Global scope

A variable declared outside any function is global. Every function, and every script on the page, can read it and change it. Globals are convenient, but they are also dangerous — any part of your code can accidentally change them, and then a bug can appear far away from where it was caused. Professional code uses as few globals as possible.

let chaiPrice = 10;  // global — every function can see it
function chaiBill(cups) {
  return cups * chaiPrice;
}

Local scope — function scope

A variable declared inside a function is local to that function. It is created when the function runs and destroyed when the function finishes. Nothing outside the function can see it — trying to read it from outside gives a ReferenceError.

function greet() {
  let message = "Namaste!";  // local — only greet() can see it
  return message;
}
greet();
console.log(message);  // Error! message is not defined here

This is a feature, not a bug. The function's private variables are its own workspace. When it finishes, the workspace is cleared, and the names are free for other functions to use.

Note: A function can read global variables, but a global cannot read a function's local variables. The looking goes one way: inwards. This is why functions are safe boxes — they can take things from outside, but nothing leaks out unless you return it.

Block scope — let and const vs var

A block is any code between curly braces, like the body of an if or a loop. Variables declared with let or const are block-scoped: they exist only inside that block. Variables declared with the older var ignore blocks and are visible through the whole function. That is one of the main reasons modern code prefers let and const over var.

if (true) {
  let a = 5;   // only inside this if-block
  var b = 6;   // visible in the whole function
}
console.log(a);  // Error!
console.log(b);  // 6 — var escaped the block

Hoisting — a quick warning

JavaScript moves declarations to the top of their scope before running the code — this is called hoisting. A var variable is hoisted and starts as undefined, so using it too early gives a confusing undefined instead of an error. A let or const variable is also hoisted, but it stays in a "temporal dead zone" until its line runs — using it too early gives a clear error. The practical rule is simple: always declare your variables at the top of their scope, and prefer let and const.

Tip: If two parts of your page need the same name, give each its own local variable inside its own function. And if a value must be shared, pass it as a function parameter instead of making it global. Parameters are the cleanest way to share data.

Common mistakes

  • Reading a local variable outside its function and getting ReferenceError: message is not defined.
  • Using var inside an if or loop and being surprised the variable is visible afterwards.
  • Declaring a global by accident — writing total = 5 without let, const or var creates a global.
  • Shadowing by accident — a local variable with the same name as a global hides the global inside that function.

Remember

  • Global scope: declared outside all functions, visible everywhere.
  • Local scope: declared inside a function, visible only there.
  • let and const are block-scoped; var is function-scoped and can leak out of blocks.
  • Global = the whole village knows it; local = only inside the house.

Example explained

  • let chaiPrice = 10; — a global variable, declared outside all functions. Both buttons on the page can see it.
  • function showGlobal() { ... } — reads the global chaiPrice from inside the function. That works, because functions can see outwards.
  • let message = "Only inside this function"; — a local variable inside showLocal(). It exists only while that function runs.
  • document.getElementById("out").innerHTML = message; — this line is inside the function, so it can read the local variable. The same line outside the function would fail.
  • var leaked = "I escaped the block"; — declared with var inside an if block, it is still visible after the block ends. A let in the same place would not be.

Example

Example
<!DOCTYPE html>
<html>
<head>
<title>Scope — Global vs Local</title>
<style>
body { font-family: Verdana, sans-serif; background-color: #fff8e1; }
h1 { color: #1e3a5f; }
.box { background-color: white; border: 2px solid #1e3a5f; padding: 14px; margin: 10px 0; width: 340px; }
button { background-color: #04aa6d; color: white; padding: 10px 18px; border: none; margin: 4px; }
</style>
</head>
<body>

<h1>Scope — Global vs Local</h1>
<div class="box">
<p>Global chai price: ₹10 (every function can see it)</p>
<p>Local message: only inside its function</p>
</div>
<button onclick="showGlobal()">Show Global Price</button>
<button onclick="showLocal()">Show Local Message</button>
<p id="out">Click a button to see what each scope can reach.</p>

<script>
let chaiPrice = 10;
function showGlobal() {
  document.getElementById("out").innerHTML = "Global price is ₹" + chaiPrice;
}
function showLocal() {
  let message = "Only inside this function";
  document.getElementById("out").innerHTML = message;
}
if (true) {
  var leaked = "I escaped the block";
}
</script>

</body>
</html>

Output

Output — how it looks in the browser
Output of JavaScript Scope — Global, Local & Block Scope Explained

Try it yourself — live editor

Change the code below and press Run to see the result instantly. No file to save, no login needed.

Result

Frequently asked questions

The questions learners ask most about this lesson — read the question, then open it to see the answer.

1. What is the difference between global and local scope?

A global variable, declared outside all functions, is visible everywhere; a local one is visible only inside its function.

2. Why should I use as few global variables as possible?

Any part of your code can accidentally change a global, so a bug can appear far away from where it was caused.

3. How do let and const differ from var in scope?

let and const are block-scoped, while var is function-scoped and can leak out of blocks.

Why learn this yourself — and not just ask AI?

AI can write code for you, but it cannot think for you. When you learn HTML yourself, your brain builds the real skill: you understand why a page looks the way it does, you can fix it when it breaks, and you can answer it in an exam or an interview without help. That is the skill that gets you a job — not a copied answer.

Get certified — just ₹10

Finish all 35 lessons, pass the test (80%), pay ₹10 and get your certificate.

Take the test

Prefer watching? Video courses teach the same topics step by step.

Go further with a full course

Free tutorials teach you the basics. Our paid courses add live projects, mentorship and a certificate.

Website Design & Development Workshop 2026
₹299
View
Summer Industrial Training in MERN Stack 2026
₹3,000
View
WordPress Website Development Course (10 Days)
₹399
View
Browse all courses
JavaScript — Lessons
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10

🤖 KAMALDNP AI Assistant

Ask about courses, website & more

Hi! I'm KAMALDNP AI Assistant. Ask me about our courses, website features, or anything else! 😊
Please wait 5s...
🤖 KAMALDNP Assistant ✕

Request human callback:

🔐 Login Required
✕

Please log in to download. You will stay on this page after logging in!

New here? Register now →