Taking Someone Off by Name
In this lesson, you ported how the Monday script searches the rota by name, and found out what JavaScript does when a name isn’t there.
- Python asks with the
inoperator:"Kofi" in rotabecomesrota.includes("Kofi"), a method on the array. Both answer yes for Kofi. - Watch out: in JavaScript,
"Kofi" in rotaisfalseand3 in rotaistrue, because theinoperator asks about keys, such as an array’s positions, not its values. - Python’s
rota.index("Kofi")becomesrota.indexOf("Kofi"). Both return3, counting from zero. - For a name that isn’t there, Python’s
index()raisesValueError: list.index(x): x not in list. JavaScript’s.indexOf()doesn’t raise: it returns-1, a value that means “not found”. - Python’s
count()has no array method to match. - JavaScript arrays have no
remove()method. The port builds one from two steps:.indexOf()finds the first match, and.splice()takes one item out from there. - For a name that isn’t on the rota,
.indexOf()returns-1, so the call becomesrota.splice(-1, 1). In Python,-1is a position too, the last item. In JavaScript, square brackets don’t count from the end, but methods like.slice()and.splice()do. So it removes Marta, with no error. - Python’s
remove()can’t do this: its search raises first. In JavaScript, “not found” is a value, so check it before you splice. - For arrays,
.includes()and.indexOf()compare the way===does: the very same array, like Python’sisoperator. Python’sinoperator checks for equal contents instead. So an array of hours pairs won’t find a fresh[18, 8]: compare its parts, which the quiz practices.
Rui moved to the daytime team last month, and this week’s leave request is for him. Here’s the team lead’s Python:
rota = ["Dev", "Lena", "Ines", "Kofi", "Bea", "Marta"]
on_leave = "Rui"
rota.remove(on_leave)
print(rota)