Javascript · Functions (Basics)
Function Scope Basics
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Variables Inside a Function
A variable declared inside a function only exists inside that function. Outside, it's as if it never existed:
function rollDice() {
let result = 4;
console.log("Inside: " + result);
}
rollDice();
// console.log(result); // Uncomment this line to see the error!
`result` is a local variable: it belongs to `rollDice`. Its scope is the function body. This is a good thing: functions don't clutter each other with their temporary variables.
Exercise 2 — Reading Outside Variables
The opposite works: a function can read a variable declared outside of it. Such a variable is called global:
let trainerName = "Sam";
function greet() {
console.log("Welcome back, " + trainerName + "!");
}
greet();
Rule of thumb: code can look outward (a function sees the globals), but not inward (the outside doesn't see a function's locals).
Exercise 3 — Quiz: Out of Reach
What happens on the last line?
function prepare() {
let potion = "Super Potion";
}
prepare();
console.log(potion);
Options
• An error: potion is not defined
• ```Super Potion```
• ```undefined```
• Nothing is printed
Hint : Where was the variable declared, and who can see that place?
Exercise 4 — Parameters Are Local Too
Parameters behave exactly like local variables: they exist only while the function runs, and only inside it.
function heal(amount) {
console.log("Healing " + amount + " HP");
}
heal(30);
// console.log(amount); // Uncomment this line to see the error!
That's why two functions can both have a parameter called `amount` without any conflict: each one lives in its own scope.
Exercise 5 — Same Name, Two Variables
What if a function declares a variable with the same name as a global one? It creates a separate, local variable. The global one is untouched:
let level = 5;
function test() {
let level = 99;
console.log("Inside: " + level);
}
test();
console.log("Outside: " + level);
Inside `test`, the local `level` hides the global one. Outside, the global is still 5. Confusing to read, so avoid reusing names on purpose, but know that it's what happens.
Exercise 6 — Quiz: Which Level?
What does the last line print?
let hp = 100;
function damage() {
let hp = 40;
}
damage();
console.log(hp);
Options
• ```100```
• ```40```
• ```undefined```
• An error
Hint : Look at the keyword used inside the function: does it create something new or change something existing?
Exercise 7 — Keep the Global Safe
Complete the function so that `name` stays `"Zap"` outside of it.
let name = "Zap";
function rename() {
____ name = "Metachu";
console.log("Inside: " + name);
}
rename();
console.log("Outside: " + name);
Options: let name return this
Hint : One keyword creates a brand new variable instead of touching the existing one.
Exercise 8 — Changing a Global From Inside
Without `let`, an assignment inside the function changes the global variable itself:
let score = 0;
function addPoints() {
score += 10;
}
addPoints();
addPoints();
console.log(score);
It works, but it's easy to lose track of who changes what. Most of the time, prefer the cleaner pattern: give the function what it needs as parameters, and get the result back with `return`.
function addPoints(current) {
return current + 10;
}
let score = 0;
score = addPoints(score);
score = addPoints(score);
console.log(score);
Exercise 9 — Quiz: Modified or Not?
What does the last line print?
let xp = 50;
function train() {
xp = xp + 25;
}
train();
console.log(xp);
Options
• ```75```
• ```50```
• ```25```
• An error
Hint : No new variable is declared here: which one gets assigned?
Exercise 10 — Scope Cheat Sheet
Match each situation with what happens.
Items to match
• Variable declared inside a function
• Variable declared outside any function
• A parameter
• let with a name that exists outside
Definitions
• Local: invisible outside
• Global: readable by functions
• Local to its function
• Creates a separate local variable
Exercise 11 — XP Tracker
Track Zap's XP without modifying globals from inside a function.
1. Declare `gainXP(current, amount)` that returns the new total (current + amount + bonus). Inside, use a local variable `bonus` worth 5 that is added on top of the amount
2. Start with `xp` at 0, then apply three gains of 20, 35 and 50, updating `xp` each time with the returned value
3. After each gain, print `"XP: N"`
Starter code
let xp = 0;
// Write your code here
Back to the course