Stack Builder — Data Structures

Operate a stack: 12 levels of push, pop, peek and LIFO. The most basic stack data structure game for anyone new to DSA. 20 levels, right in the browser.

What you learn in this game

A stack holds values in a pile. push(x) puts x on top, pop() takes the top one off and returns it. The last one in is the first one out (LIFO: last in, first out), like a pile of plates: only the top plate can be taken.

pop() takes the top plate off and returns it; the plate under it becomes the top one. To change something in the middle of a pile, everything above it has to be popped first. On an empty pile pop() is a mistake: the angkringan's Tumpukan class throws TumpukanKosong. A plain JavaScript array says nothing and returns undefined, so a good stack checks for it itself.

peek() reads the top value without taking it off: the pile does not change. Only the top of a stack can be seen; to see what is under it, the top has to be popped first.

A stack reverses order: values pushed K, L, M, N come back out N, M, L, K. That is why stacks reverse strings, retrace steps, and run the browser's Back button.

Stacks check brackets: every opening bracket is pushed; every closing bracket pops the top one, which must be its partner. At the end of the text, what is left on the stack is the brackets still open, from the outermost (bottom) to the innermost (top).

The call stack is the stack the JavaScript engine uses to remember which function is waiting for which. Calling a function pushes a frame; a function that finishes (returns) is popped, and its caller carries on from the line after the call. The top frame is the function running now. new Error().stack prints this stack from the top: the running function first, then its caller, down to the code outside any function on the last line.