Skip to the content

Private fields

JavaScript · Unit 14: Modern classes

A value that starts out the same in every object can be declared right in the class body, with no constructor: count = 0;. Every new object starts with its own copy.

class Counter {
  count = 0;
  up() {
    this.count++;
  }
}
const c = new Counter();
c.up();
c.up();
console.log(c.count);

Prints

2

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    Two boxes are created and only one gets something. What does it print?

  2. 2. Complete the code

    Fill in the field declaration so the flask starts at 0 ml.

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    Look closely at the name on the last line. What does it print?

  5. 5. Find the bug

    This program should print 50, the money in the account. Which line has the error?

  6. 6. Complete the code

    Fill in the declaration so the chest's coins can only be touched from inside.

  7. 7. Multiple choice

    The Account class keeps its money in #balance and only moves it with deposit and withdraw. What does that buy you?

  8. 8. Put the lines in order

    Put the Piggy class in order: it keeps its coins private and lets you see them through a get.

  9. 9. Find the case that fails

    enroll(times) signs that many people up for a workshop with 3 spots and returns how many spots are left, which can never be less than 0. Which call does it fail on?

  10. 10. Predict the output

    The report has a get points, but no set. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →