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.

Discover other journeys with this module

What students will learn in this module

Every question in Module 43

Quick questions

  1. Does a variable declared with let inside a function stay local to it?AYesBNo
  2. Can code outside a function access a variable declared inside it?ANoBYes
  3. Does each function create its own separate scope?AYesBNo
  4. Can a variable be used before it's declared inside its own scope?AYesBNo
  5. 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 does
function calc() { let total = 10; return total; }Match it to what it does
The area of code where a variable can be accessedMatch it to what it does
Keeps a variable local so it can't be accessed outside its functionMatch it to what it does
function greet() { let name = "Sam"; } console.log(name);Match it to what it does
function calc() { let total = 5; } console.log(total);Match it to what it does

Fill in the blanks

  1. function greet() {
    ___ name = "Sam";
    console.log(name);
    }

    Hint: Type the keyword used to declare a local variable.

  2. function calc() {
    let total = 10;
    ______ total;
    }
    console.log(calc());

    Hint: Type the keyword that sends a value back out of the function.

  3. function show() {
    ___ count = 5;
    console.log(count);
    }

    Hint: Type the keyword used to declare a local variable.

  4. function test() {
    if (true) {
    ___ x = 1;
    console.log(x);
    }
    }

    Hint: Type the keyword used to declare a local variable.

  5. 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}