Course outline · 0% complete

0/29 lessons0%

Course overview →

Growing and shrinking arrays

lesson 4-2 · ~9 min · 11/29

push, pop, and friends

A running program's data rarely stands still: a chat gains messages, a cart gains and loses items, a print queue drains. These methods are how an array changes while the program runs.

Python's append is JavaScript's push. The core moves:

ActionPythonJavaScript
add to endxs.append(v)xs.push(v)
remove from endxs.pop()xs.pop()
add to frontxs.insert(0, v)xs.unshift(v)
remove from frontxs.pop(0)xs.shift()
is v in xs?v in xsxs.includes(v)
position of vxs.index(v)xs.indexOf(v)

pop and shift return the removed item, so you can catch it in a variable. indexOf answers -1 when the item is missing (no error).

One surprise: you declared the array with const in lesson 2-1 terms, yet push still works. const only locks the variable from being reassigned to a different array. Changing the contents of the same array is allowed.

Code exercise · javascript

Run it. Watch pop hand back the removed value, and indexOf answer -1 for a missing item. Printing a whole array shows its brackets and contents.

Code exercise · javascript

Your turn. Start from the shopping list below. Push bread, then push eggs, then pop once. Print the final array on one line and its length on the next.

Code exercise · javascript

Second practice. A help desk serves people in arrival order (a queue): newcomers push onto the end, service takes from the front with shift. Push Linus onto the queue, shift the first person into a variable, then print Now serving: <name> and, on a second line, how many are still waiting.

Quiz

const xs = [1, 2]; xs.push(3); Does this run, given xs is a const?