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.
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.
var ignores blocks and is scoped to the whole function (or the global scope), which is why modern code uses let and const.
An inner variable with the same name as an outer one shadows it: inside the block, the name refers to the inner variable only.
Assigning to an undeclared name throws a ReferenceError in strict mode (and in modules and classes). In old sloppy-mode scripts it silently created a global.
Keep variables in the narrowest scope: fewer names are visible at each line, which reduces accidental reuse and makes code easier to move.
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.
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.
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
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.
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 explanationscope
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 predictionscope 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.
Debuggingscope 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 generationscope 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 reviewscope 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.