Global vs Local Scope

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Where a Variable Lives

Imagine writing a function that rolls a die during a Codémon battle. Inside that function, you create a variable `result` to store the roll. Because `result` is declared inside the function, it only exists while that function is running. If you try to read `result` outside the function, JavaScript throws an error:

function rollDice() { const result = 4; console.log("Inside: " + result); } rollDice(); console.log(result); // This will cause an error!

The region of code where a variable can be accessed is called its scope. A variable declared inside a function has local scope (or function scope): it is invisible to the rest of the program.

Exercise 2 — Global vs. Local Variables

What about the opposite direction? A variable declared outside of any function is a global variable, and every function in your file can read it:

const trainerName = "Sam"; function greet() { console.log("Welcome back, " + trainerName + "!"); } greet();

Think of a function like a room with one-way tinted windows: - Code inside the function can look out and use global variables. - Code outside the function cannot look in to see its local variables. Because each function has its own private room, two functions can both declare a local variable named `result` without ever conflicting:

function attack() { const result = "Direct hit!"; console.log(result); } function heal() { const result = "HP restored!"; console.log(result); } attack(); heal();

Exercise 3 — Function Parameters Are Local Too

A function's parameters follow the exact same rule as local variables: they only exist inside that function while it is running:

function heal(amount) { console.log("Healing " + amount + " HP"); } heal(30); console.log(amount); // error!

Every time you call `heal(30)`, JavaScript creates a fresh local parameter `amount` for that call and discards it as soon as the function finishes.

Exercise 4 — Quiz: Out of Reach

What happens on the last line?

function prepare() { const potion = "Super Potion"; } prepare(); console.log(potion);
Options
• An error: potion is not defined
• "Super Potion"
• undefined
• Nothing

Hint : Ask where the variable was declared and who can see that place.

Exercise 5 — Quiz: Reading a Global

What does this code print?

const hero = "Zap"; function show() { console.log(hero); } show();
Options
• Zap
• undefined
• An error
• hero

Hint : Functions can look outward.

Exercise 6 — Keep It Inside

Declare a local variable `bonus` worth 10 and use it in the message.

Hint : Declaring needs a keyword, and the message must use the variable itself, without quotes.

Exercise 7 — Why Local Variables Are a Good Thing

Local scope is not a limitation—it is a safety feature! When a function relies only on its parameters and its own local variables, it is completely self-contained: you can understand and test it on its own without worrying about the rest of the program:

function calculateDamage(base, level) { const bonus = level * 2; return base + bonus; } console.log(calculateDamage(20, 5)); console.log(calculateDamage(20, 10));

Avoid using too many globals

If every variable in your game is global, any function can accidentally overwrite a value used by another function. Always declare variables inside the smallest scope where they are needed!

Exercise 8 — Quiz: Two Functions, One Name

What does this code print?

function a() { const x = 1; console.log(x); } function b() { const x = 2; console.log(x); } a(); b();
Options
• 1 then 2
• 1 twice
• 2 twice
• An error

Hint : Each function has its own private area.

Exercise 9 — Scope Cheat Sheet

Match each situation with what happens.

Items to match
• Declared inside a function
• Declared outside every function
• A parameter
• Reading a local from outside
Definitions
• Local: invisible outside
• Global: readable everywhere
• Local to its function
• An error

Exercise 10 — Self-Contained Calculator

Write two functions that rely only on their parameters and their own local variables. No global data allowed apart from the two constants already provided.

Step 1: `damage(base, level)` declares a local `bonus` worth twice the level, then returns the base plus that bonus. Step 2: `report(name, value)` declares a local `line` holding `"name deals X damage"`, then prints it. Step 3: use both to report the damage of Zap at level 5 with base 20, then of Metachu at level 12 with base 30. Step 4: print `"Trainer: X"` using the global constant, to show a function can read outward.

Expected output:

Zap deals 30 damage Metachu deals 54 damage Trainer: Sam
Starter code
const trainerName = "Sam"; // Write your functions here // Use them here
Back to the course