Using Arrays as Lists
In this lesson, you ported the crew’s stop list for the van to JavaScript arrays, and found out why the port loaded 11 bikes where Python loads 6.
- A Python list is a JavaScript array, written the same way: square brackets, quotes and
commas. Each array gets a
const. - Python’s
append()becomes.push(), a method (a function that belongs to the array), which adds an item to the end of the array. - Python’s
len()becomes.length, with no parentheses, because it’s a value the array keeps up to date, not a function. - JavaScript has an
inoperator, but it asks about keys, not values, the way Python’sindoes on a dict. An array’s keys are its positions, each item’s index counted from zero, plus a few built-in names such aslength. So0 in closedDocksistrueand"Market Hall" in closedDocksisfalse:innever finds a value in an array. - A closed check ported from Python as it reads,
if (name in closedDocks) {, runs with no error and gives the wrong answer. - To ask whether an array holds a value, call
.includes()on it: the array comes first, then the value, the other way round fromin. It checks each item against the value, as Python’sindoes on a list.
Here’s the crew’s Python step:
empty_docks = ["Elm Street", "Market Hall"]
closed = ["Market Hall"]
stops = []
for name in empty_docks:
if name in closed:
print(f"Skip {name}: closed")
else:
stops.append(name)
print(f"Van stops: {len(stops)}")