Functions – Scope, online
Six activities your students do on their own devices. See who's finished, and their scores.
Functions – Scope in one minute
What students need to know
scope describes exactly where a variable is visible and usable. Declaring with let inside a function scopes the variable to it.
The variable only exists within that function's scope. Once the function ends, its local variables are gone.
Mistakes students make
- msg is scoped inside say() and isn't accessible before or outside it.
- result is scoped inside add() and isn't accessible outside it.
- user is used before it's declared inside the function's scope.
- area is used before it's declared inside the function's scope.
What students will learn in this module
Every question in Module 43
Quick questions
- Does a variable declared with let inside a function stay local to it?AYesBNo
- Can code outside a function access a variable declared inside it?ANoBYes
- Does each function create its own separate scope?AYesBNo
- Can a variable be used before it's declared inside its own scope?AYesBNo
- Does calling a function twice create two separate variable scopes?ANoBYes
Key terms
Students type the meaning of:
scope
Match the pairs
function greet() { let name = "Sam"; }Match it to what it doesfunction calc() { let total = 10; return total; }Match it to what it doesThe area of code where a variable can be accessedMatch it to what it doesKeeps a variable local so it can't be accessed outside its functionMatch it to what it doesfunction greet() { let name = "Sam"; } console.log(name);Match it to what it doesfunction calc() { let total = 5; } console.log(total);Match it to what it doesFill in the blanks
function greet() { ___ name = "Sam"; console.log(name); }Hint: Type the keyword used to declare a local variable.
function calc() { let total = 10; ______ total; } console.log(calc());Hint: Type the keyword that sends a value back out of the function.
function show() { ___ count = 5; console.log(count); }Hint: Type the keyword used to declare a local variable.
function test() { if (true) { ___ x = 1; console.log(x); } }Hint: Type the keyword used to declare a local variable.
function calcArea(side) { let area = side * side; ______ area; } console.log(calcArea(4));Hint: Type the keyword that sends a value back out of the function.
Spot the error
Question 1
Aconsole.log(msg);Bfunction say() {Clet msg = "Hi";D}
Question 2
Aconsole.log(result);Bfunction add(a, b) {Clet result = a + b;Dreturn result;E}
Question 3
Afunction greet() {Bconsole.log(user);Clet user = "Amy";D}
Question 4
Afunction calcArea(s) {Bconsole.log(area);Clet area = s * s;Dreturn area;E}
Question 5
Afunction outer() {Blet x = 1;Cconsole.log(y);D}
