Skip to main content

JavaScript Scope — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript Scope lesson. Every one is checked automatically in the browser — write the code, run it, and the tests tell you what still fails.

Exercises(5)

  1. 1

    Read a global variable

    easy10 min

    Read a variable declared outside the function from inside it.

  2. 2

    Keep a variable local

    easy10 min

    Show that a variable declared inside a function does not exist outside.

  3. 3

    Walk the scope chain

    easy10 min

    Join a value from each of three nested scopes with a dash.

  4. 4

    Shadow an outer variable

    easy10 min

    Declare a variable inside a function with the same name and show the outer one is untouched.

  5. 5

    Pass instead of sharing

    medium10 min

    Pass a value into a function rather than reading a global, and show the result.

Find the bug(5)

  1. 1

    Fix the variable read out of scope

    easy8 min

    The variable only exists inside the function.

  2. 2

    Fix the shadowed value

    easy8 min

    The inner variable hides the outer one, so the wrong value is returned.

  3. 3

    Fix the broken scope chain

    easy8 min

    The inner function cannot see a variable declared after it runs.

  4. 4

    Fix the hidden global dependency

    easy8 min

    The function reads an outside rate, so changing it changes the answer.

  5. 5

    Fix the outer variable overwritten

    easy8 min

    The function changes the global instead of using its own copy.

Ready to write the code?

The editor, the automatic checks and the worked solutions open up with an account.

Open the workspace