Coding for Kids

Arrays: Push, Pop, Shift, and Unshift

Like most variables in a program, you want to be able to alter their values. For primitive variables, like strings and numbers, you can only replace values. In a list like an array, you can add more items to it or take things away.

Adding to and removing from an array

There are a couple of ways to do this.

Push and Pop:

A pair of array methods .push(item) and .pop() are commonly used.

push adds a new item (or items) to the end of the array

pop pulls the last item off an array and returns it for use

Shift and Unshift:

Another pair of methods is called .shift() and .unshift(item). These are like pop and push, but they work at the front of the array.

shift removes the first item and shifts everything down, leaving no gaps

unshift pushes everything back and inserts a new item (or items) at index 0

The new dance craze is here, the Push-Pop, Shift-Unshift shuffle!

—Dr. Wolf