Skip to the content

Stacks

JavaScript · Unit 23: Data structures

A stack is a tower of plates: you put one on top and you take one from the top. The last one in is the first one out.

You need nothing new: an array with push to put and pop to take is already a stack.

const plates = [];
plates.push("deep");
plates.push("flat");
console.log(plates.pop());
console.log(plates);

Prints

flat
[ 'deep' ]

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

    What does this code print?

  2. 2. Complete the code

    Fill in the blank to take the last alert off the stack.

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    Which of these jobs calls for a stack?

  5. 5. Find the bug

    undo should take the last change out and hand it back. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Fill in the blank so take hands back the top one.

  8. 8. Put the lines in order

    Put reverseWords(f) in order. It flips the order of the words in a phrase using a stack.

  9. 9. Find the case that fails

    remaining(n) takes n plates off a stack of 3 and returns how many are left, which can never be less than 0. Which call breaks it?

  10. 10. Predict the output

    The stack holds the pages you visited and pop is the Back button. 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 →