Tracing Every Section’s Returned Word Count
In this lesson, you port a recursive word count to JavaScript and trace each call’s returned total. The desk prices quotes by word count, and the museum guide is a tree: Museum Guide has 120 words and two sections, Welcome with 80 and Collections with 150, which holds Access, with 50.
In Python, count_words() starts with a section’s own words, adds each child’s returned count, and
returns the total:
def count_words(section):
total = section["words"]
for child in section["children"]:
total += count_words(child)
return total
With the guide in DOCUMENT as nested dictionaries, print(count_words(DOCUMENT)) prints 400.
Four calls each keep a total variable. So how do they stay apart, and how does 400 come back?
In JavaScript, the guide becomes nested object literals with the same keys, and each leaf’s
children is an empty array. The function ports line for line: function in place of def, a
let for the total because += reassigns it, dot access for the words, for...of for the
children, and return to hand the total back. For this guide, only the spelling changed: