Chapter 16

Choose Your Own Adventure

Imagine you’re climbing a tree. If you climb up one branch, you’ll see certain things, such as a bird’s nest or a balloon that got stuck up there during your birthday party. If you climb a different branch, you might see other things, like the neighbor’s garage. In JavaScript, the technique of using if…else or switch statements to choose between two or more paths is called branching.

In this chapter, we use branching to write a choose-your-own-adventure game that asks for user input at key moments to change the story.


Planning the Story

Any good story needs a plot. The plot is the outline of events that happen over the course of the story. When writing a story where the user’s input influences the plot, the writer needs to pay close attention to managing the different plot lines. Each plot line has the same beginning, but the middle and ending are different based on input from the user.

Creating a flow chart

Considering all of the different options — and planning for each possibility — in a branching program is a valuable skill to have as a programmer.

We’ll begin by creating a simple story that poses a question. This creates two branches. Each of these branches will have a question that creates two more branches. Eventually, every choice will lead back to one of two possible endings.

A useful tool for visualizing branches of a story ...

Get JavaScript For Kids For Dummies now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.