JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 10: Scope and JavaScript BehaviorLesson 46 of 150About 40 minutes

Lesson 46: Global, function and block scope

01Opening question

Two functions both use a variable called total. Why don't they overwrite each other?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

appName is global, total belongs to the function, and message exists only inside the if block.

const appName = "Shop";
function checkout() {
  const total = 40;
  if (total > 30) {
    const message = "Free delivery";
    console.log(appName, total, message);
  }
}
checkout();

03Objective and prerequisites

Learning objective: Explain global, function and block scope, predict which variable a name refers to, and keep variables in the smallest scope that needs them.

You need: Lesson 16: For loops, Lesson 21: Function declarations and expressions

Skills practised: Scope.

04Explanation

Scope is the part of a program where a variable can be used.

Global scope: variables declared outside every function and block can be read anywhere.

Function scope: variables declared inside a function exist only while that function runs and cannot be seen outside it.

Block scope: let and const declared inside { } (an if, a loop, or a bare block) exist only inside that block. Using them outside gives a ReferenceError.

05Definitions

Scope
The region of code where a variable is visible.
Global scope
The outermost scope, visible to all code.
Function scope
Variables visible only inside the function that declares them.
Block scope
let and const visible only inside the { } block that declares them.
Shadowing
An inner variable hiding an outer variable with the same name.

Open the full glossary

06Visual learning object

Scope chain explorer. Step through nested functions and blocks and see which scope each name is found in.

Loading the interactive object…

Open the full Scope chain explorer page with its guided experiment.

07Examples

ex-046-01Function scope Browser-executable JavaScript

Each call has its own local variables.

function addTax(price) {
  const rate = 0.2;
  return price + price * rate;
}
console.log(addTax(10));
console.log(typeof rate);
Sample input
None
Expected output
12 undefined
Common mistake
Expecting to read rate outside the function.
Try this
Add a second function that also declares rate = 0.1 and call both.
Source
examples/ex-046-01-function-scope.js

ex-046-02Block scope Browser-executable JavaScript

let and const stay inside their block.

const scores = [72, 95];
for (const s of scores) {
  const grade = s >= 90 ? "A" : "B";
  console.log(s, grade);
}
try {
  console.log(grade);
} catch (e) {
  console.log(e.name);
}
Sample input
None
Expected output
72 B 95 A ReferenceError
Common mistake
Declaring a variable inside a loop and expecting it after the loop.
Try this
Collect the grades in an array declared before the loop.
Source
examples/ex-046-02-block-scope.js

ex-046-03Shadowing Browser-executable JavaScript

The inner name hides the outer one inside its block.

const status = "global";
function show() {
  const status = "function";
  {
    const status = "block";
    console.log(status);
  }
  console.log(status);
}
show();
console.log(status);
Sample input
None
Expected output
block function global
Common mistake
Reusing a name and then being surprised which value is read.
Try this
Rename the inner variables so nothing is shadowed.
Source
examples/ex-046-03-shadowing.js

ex-046-04var ignores blocks Browser-executable JavaScript

var is function-scoped; let is block-scoped.

function demo() {
  if (true) {
    var a = "var";
    let b = "let";
  }
  console.log(a);
  console.log(typeof b);
}
demo();
Sample input
None
Expected output
var undefined
Common mistake
Using var in loops and blocks and leaking values out of them.
Try this
Change var to let and run again.
Source
examples/ex-046-04-var-vs-let.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the out-of-scope variable

Declare a variable in the scope where it is needed.

const prices = [4, 6, 10];
for (const p of prices) {
  let total = 0;
  total += p;
}
console.log(typeof total === "undefined" ? "no total" : total);

Untangle shadowing

Rename shadowed variables so each value is clear.

const discount = 5;
function price(base) {
  const discount = 10;
  return base - discount;
}
console.log(price(50), discount);

Scoped report

Write a function that keeps all working variables local.

// Write summarize(scores)

09Prediction

Commit to an answer first, then run the real code to compare.

let x = 1;
{
  let x = 2;
  x++;
}
console.log(x);

What is printed?

10Debugging investigation

The counter shows 1 every time

A like button should count up, but after three clicks the counter still shows 1.

function like() {
  let count = 0;
  count += 1;
  return count;
}
like();
like();
const shown = like();
console.log(`Likes: ${shown}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Large scripts

In a large page script, every global name is shared with every other script. Keeping helpers inside functions and blocks prevents two features from silently overwriting each other's variables.

function cartFeature() {
  const count = 3;
  return `cart ${count}`;
}
function inboxFeature() {
  const count = 12;
  return `inbox ${count}`;
}
console.log(cartFeature(), inboxFeature());

12Knowledge check

1. What is printed?

if (true) { const msg = "inside"; }
console.log(msg);
  • inside
  • undefined
  • A ReferenceError is thrown
  • null

2. What is printed?

const n = 10;
function f() { const n = 20; return n; }
f();
console.log(n);
  • 10
  • 20
  • undefined
  • An error

3. Which declarations are block-scoped?

  • var only
  • let and const
  • function declarations only
  • All of them

4. Why does this print 3 instead of throwing a ReferenceError?

for (var i = 0; i < 3; i++) {}
console.log(i);
  • var is function-scoped, so i exists after the loop
  • i++ runs twice
  • console.log is wrong
  • The loop has no body

5. What is printed?

const v = "a";
{ const v = "b"; console.log(v); }
console.log(v);
  • a b
  • b b
  • a a
  • b a

6. Where should a loop's running total be declared?

  • As a global at the top of the file
  • Just before the loop, inside the function that needs it
  • Inside the loop body
  • With var anywhere

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the out-of-scope variable: Prints 20
  • Untangle shadowing: Prints 35 5; price(100)
  • Scoped report: Prints both; No var; No leaked sum
  • ex-046-01: output matches the documented expected output
  • ex-046-02: output matches the documented expected output
  • ex-046-03: output matches the documented expected output
  • ex-046-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-10-scope-and-javascript-behavior/lesson-046-global-function-and-block-scope/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Scope decides where a variable is visible.
  • let and const are block-scoped; var is function-scoped.
  • Inner names shadow outer names.
  • Declare variables in the smallest scope that needs them.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation scope
Context: I am learning scope in JavaScript.
Task: Explain global, function and block scope with a shopping app example, including shadowing.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction scope drill
Context: I have practised scope.
Task: Give me six snippets with nested scopes and shadowed names and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging scope bug
Context: My variable is not defined outside a loop, or has a value I did not expect.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation scope practice
Context: I finished the scope exercises.
Task: Create three exercises that fix scope mistakes.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review scope review
Context: Here is my code that uses scope.
Task: Review my code for variables declared in a wider scope than they need.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.