Summary: Loops and Terminal Input

You’ve come a long way since the first lesson. Back then, your checkGuess() function could judge a single guess, and every guess needed its own handwritten call. Now you have a game that asks a real player for as many guesses as they need, explains odd answers, gives hints, and hands the terminal back when the player wins or types quit.

Before you read the list below, take a minute to pull a few ideas from memory. With pen and paper, write down the four parts of a while loop, where break and continue each jump to, and the two ways your game can end. Then compare your notes with the rest of this page.

What You Can Do Now

In this course, you’ve learned how to:

  • Repeat code with while: You give a while loop a start, a condition, a body, and an update that moves the condition toward false. You trace its passes in a table, predict that a loop whose first check fails runs zero times, and stop a runaway loop with Ctrl+C. When the body must run once before there’s anything to check, you reach for do...while.
  • Count with for: A for header packs the start, the check, and the update into one line and runs them in a fixed order: the start once, then check, body, and update, until the check is false. You declare an accumulator before the loop and use its result after it, and you visit a string’s characters with i < word.length without reading past the end.
  • Leave a loop early: break ends the whole loop, for example at the first match, and continue skips to the next pass. In a counted while loop, keep the update above any continue so every pass reaches it. Your game’s while (true) loop is different: its condition never becomes false, so it ends only when a quit or a win reaches a break.
  • Plan before you code: You restate a brief as inputs and an output, solve two or three cases by hand, write the steps as comments, and build under them one runnable step at a time.
  • Ask questions in the terminal: With the readline recipe in an .mjs file, you ask with await rl.question(), and every answer arrives as a string. You convert it with Number(), reject blank, NaN, and out-of-range answers, ask again, and close the interface once, after the loop.

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

Become a Member to join the conversation.