javascript
37 lines · 7 steps
Building a Stack with private fields
A clean LIFO stack in JavaScript using a private field, chainable pushes, and a custom iterator.
Explained by
highlit
1class Stack {
2 #items = [];
3
4 push(value) {
5 this.#items.push(value);
6 return this;
7 }
8
9 pop() {
10 if (this.isEmpty()) {
11 throw new Error("Stack underflow");
12 }
13 return this.#items.pop();
14 }
15
16 peek() {
17 return this.#items[this.#items.length - 1];
18 }
19
20 isEmpty() {
21 return this.#items.length === 0;
22 }
23
24 get size() {
25 return this.#items.length;
26 }
27
28 clear() {
29 this.#items.length = 0;
30 }
31
32 *[Symbol.iterator]() {
33 for (let i = this.#items.length - 1; i >= 0; i--) {
34 yield this.#items[i];
35 }
36 }
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Private fields (#) enforce true encapsulation so internal state can't be touched from outside.
- 2Returning this from mutating methods enables fluent, chainable call syntax.
- 3Implementing Symbol.iterator makes a custom class work with for...of and spread.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-stack-with-private-fields-explained-javascript-5d42/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.