Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Tracing Every Section's Returned Word Count

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:

Language: Python
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:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In this lesson, you’ll 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.

00:11 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.

00:28 It prints 400. Four calls each keep a total variable. So how do they stay apart, and how does 400 come back?

00:38 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 declares it in place of def.

00:51 The total is a let, because += reassigns it, and dot access reads the words. for...of walks the children, and return hands the total back.

01:02 For this guide, only the spelling changed. Run it, and JavaScript logs the same 400 that Python prints.

01:11 When countWords() calls itself, each call gets its own frame, as in Python, with its own environment for its names. The first call takes the whole guide: section is Museum Guide, and total starts at 120.

01:26 Its loop reaches Welcome and calls the function again: a new frame on top, with a second section and a second total, 80. Same names, separate variables.

01:36 Each environment links out to the module scope, where every call finds the function itself.

01:42 Collections hasn’t started yet. Of the four calls, which one leaves first? Your turn: pause the video and predict.

01:57 Welcome leaves first, before Collections has even started.

02:02 Its children is an empty array, so its loop runs zero times. That’s the base case, and as in your Python, the empty loop means no if is needed.

02:12 The call hands back 80, and its frame leaves the stack. The root’s total grows from 120 to 200. Each call descends one level down a finite tree, so every path ends at a leaf.

02:27 Next, the root’s loop calls the function on Collections, whose total starts at 150. It calls the function on Access, a leaf, which hands back 50. Collections adds it and hands back 200.

02:41 The root already holds 200, its own 120 plus Welcome’s 80. It adds Collections’ 200 and returns 400.

02:51 No call reads another frame’s total. Only the value each return hands back crosses between frames.

02:59 A trace confirms that order. Log a line as each call enters, and another, with its total, right before it leaves. Like print(), console.log() puts a space between its arguments.

03:12 Run it, and the lines match: Welcome leaves before Collections enters, and the root leaves last. A call leaves only after every call it made has left: the last frame in is the first out.

03:27 What if a call never gets closer to its base case? This probe calls itself with the same number, so the stack fills. Python raises a RecursionError past its recursion limit, 1000 by default, and counts the repeats.

03:42 JavaScript has no such counter: Node throws a RangeError when the stack runs out of room. Its trace repeats the same function and line, and lists only the ten newest calls: a print limit, not a count.

03:58 That call is a tail call, the last thing the function does. Some languages reuse the frame there; Node 26 and Python don’t. Even a valid guide, nested deep enough, can fail this way, at no fixed depth.

04:14 So check progress toward a leaf first, then the input’s depth. For extreme, untrusted depth, a loop over an explicit work list can replace the call stack.

04:26 So each recursive call has its own frame and total, and a leaf’s empty children is the base case. Each call hands its total back for the caller to add.

04:37 Next up is the exercise Count Every Section of a Different Guide. There, you’ll repair the word count for a different finite guide, and trace its first three calls.

Become a Member to join the conversation.