• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking○Inspect Values in the Console○Inspect the Queue Report○Trace a Faulty Calculation○Repair the Score Calculation✦Module Quiz
○Declaring Variables○let and const in Practice○Operators○Type Conversion○Group and Convert Expense Inputs○Calculate the Event Expense Total○Track a Changing Points Tally○Adjust a Ticket Price✦Module Quiz
○Conditionals○Demo: Combined Conditions Before FizzBuzz○Challenge: FizzBuzz Announcer○Switch Statement○Demo: Switch a Venue Sign○Challenge: Power Loadout○For Loops○While Loop○Break and Continue○Demo: Stop a Ticket Scan○Challenge: Number Guess Referee○Demo: Rainfall Routing Walkthrough○Exercise: Score Batch Report✦Module Quiz
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions○Demo: Ticket Pricing Walkthrough○Exercise: Shipping Labels with Defaults○Demo: Seat Ledger Closure Walkthrough○Exercise: Private Budget Ledger✦Module Quiz
○Arrays○Demo: Student Scoreboard○Challenge: Student Course Scoreboard○Array Mutation Methods○Array Slice and Concat○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every○Demo: Charging Rack Restock Report○Exercise: Pantry Restock Plan✦Module Quiz
○Object Key-Value Pairs○Student Course Record○Object Methods and Destructuring○Map and Set Collections○Playlist Lookup○Number and BigInt Boundaries○Ticket Ledger○JSON○Math and Date○Date Basics○Demo: Supply Bin Audit○Exercise: Volunteer Shift Audit○Demo: Workshop Attendance Feed○Exercise: Parcel Scan Feed✦Module Quiz
○String Methods○Template Literals○Regular Expressions○Demo: Build a Reminder with Template Literals○Exercise: Format Pantry Pickup Messages○Demo: Validate a Time Slot with Regex○Exercise: Validate Storage Shelf Labels✦Module Quiz
○Higher-Order Functions○Callbacks○map, filter, and reduce○Demo: Student Register with map○Challenge: Student Register○Recursion○Project - Data Transform Pipeline○Demo: Handle an Error-First Callback○Exercise: Report Seat Reservation Results○Demo: Summarize Completed Bike Rides○Exercise: Summarize Delivered Parcels✦Module Quiz
○Demo: A notebook object○OOP Introduction○Demo: Independent workshop passes○Classes○Demo: An inherited notice○Inheritance○Demo: A private seat counter●Encapsulation○Demo: Equipment desk checkout○Project: Library Checkout✦Module Quiz
○Demo: Callback Timing○Exercise: Asynchronous JavaScript○Demo: Promise Rehearsal○Exercise: Promises and Async Await○Demo: Offline API Coordination○Exercise: Async API Simulation○Demo: Partial Results Bulletin○Project: Resilient Awards Feed○Demo: Retry a Local Delivery○Project: Reliable Score Delivery✦Module Quiz

Encapsulation

The seat-counter demo kept its seat count private. Build a stack with a private array in script.js, then inspect pushes and pops in the Console. No page elements are involved.

Encapsulation hides internal implementation details and exposes only a controlled interface. In JavaScript, private class fields (using #) are the modern approach.

Private fields with #

javascript
class Counter {
    #count = 0;           // private — not accessible outside

    increment() { this.#count++; }
    decrement() { this.#count--; }
    get value() { return this.#count; }
    reset() { this.#count = 0; }
}

const c = new Counter();
c.increment();
c.increment();
console.log(c.value);  // 2
// c.#count outside Counter would be a SyntaxError; leave it commented out.

Validation in setters

javascript
class Temperature {
    #celsius;

    constructor(celsius) { this.celsius = celsius; }  // uses setter

    get celsius() { return this.#celsius; }
    set celsius(value) {
        if (value < -273.15) throw new Error("Below absolute zero!");
        this.#celsius = value;
    }
    get fahrenheit() { return this.#celsius * 9/5 + 32; }
}

Your Task

  1. Initialize the private #items field to an empty array. The starter checks whether the stack is initialized.
  2. Implement the size getter to count stored items; the starter checks an empty stack.
  3. Implement push to add an item; the starter checks the size after two pushes.
  4. Implement pop to remove and return the top item; the starter checks the item and remaining size.
  5. Make pop return undefined for an empty stack; the starter probes an empty stack.
  6. Implement peek without removing an item; the starter checks the top item and size.
  7. Implement isEmpty; the starter checks before and after a push.
  8. Log Stack size: 2 | top: 20 on its own Console line after the starter’s final stack setup.

Next, combine inheritance and private state in a checkout project.

Hint 1
1 / 3
HINT 1

Private class fields use #: #balance = 0;

HINT 2

Private fields cannot be accessed from outside the class.

HINT 3

Provide public getters/setters or methods to read/write private data.

Loading editor…
Press Run to execute your code.
READY
intercourses
javascript