Skip to main content

JavaScript Private Fields — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript Private Fields 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

    Declare a private field

    easy10 min

    Keep the balance private and expose it through a method.

  2. 2

    Hide it from Object.keys

    easy10 min

    Report the keys of an object with one private and one public field.

  3. 3

    Control how it changes

    easy10 min

    Refuse a negative deposit and report the balance.

  4. 4

    Write a private method

    easy10 min

    Keep the tax calculation private and use it from total.

  5. 5

    Expose it through a getter

    medium10 min

    Give the class a balance getter that reads the private field.

Find the bug(5)

  1. 1

    Fix the underscore convention

    easy8 min

    An underscore does not actually prevent anything.

  2. 2

    Fix the private field exposed

    easy8 min

    The field is public, so it shows up in Object.keys.

  3. 3

    Fix the missing validation

    easy8 min

    A negative deposit is being accepted.

  4. 4

    Fix the helper left public

    easy8 min

    The tax helper should not be callable from outside.

  5. 5

    Fix the private field read from outside

    easy8 min

    A private field can only be reached from inside the class body.

Ready to write the code?

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

Open the workspace