Keep the balance private and expose it through a method.
Acceptance criteria
- 1.#out should show 100.
JavaScript Tutorial · JavaScript Classes
These 10 tasks go with the JavaScript Private Fields chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “A field starting with a hash is private and cannot be read from outside the class.” .
1.Declare a private fieldexercise · easy · 10 min
Keep the balance private and expose it through a method.
Passes when: #out should show 100.
2.Hide it from Object.keysexercise · easy · 10 min · practice plan
Report the keys of an object with one private and one public field.
Passes when: #out should show name.
3.Control how it changesexercise · easy · 10 min · practice plan
Refuse a negative deposit and report the balance.
Passes when: #out should show 100.
4.Write a private methodexercise · easy · 10 min · practice plan
Keep the tax calculation private and use it from total.
Passes when: #out should show 120.
5.Expose it through a getterexercise · medium · 10 min · practice plan
Give the class a balance getter that reads the private field.
Passes when: #out should show 250.
6.Fix the underscore conventionbug fix · easy · 8 min
An underscore does not actually prevent anything.
Passes when: #out should show 100.
7.Fix the private field exposedbug fix · easy · 8 min · practice plan
The field is public, so it shows up in Object.keys.
Passes when: #out should show only name.
8.Fix the missing validationbug fix · easy · 8 min · practice plan
A negative deposit is being accepted.
Passes when: #out should show 100.
9.Fix the helper left publicbug fix · easy · 8 min · practice plan
The tax helper should not be callable from outside.
Passes when: #out should show private.
10.Fix the private field read from outsidebug fix · easy · 8 min · practice plan
A private field can only be reached from inside the class body.
Passes when: #out should show 250.
Between them these tasks cover Private fields, Encapsulation and Private methods.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.