Loading video player…

Loops and Terminal Input (Overview)

In this course, you’ll build a secret code guessing game that keeps asking in your terminal until the player wins or quits. That asking again is a loop. The player types a guess, gets a hint to go higher or lower, and is asked again after an answer the game can’t use. The game ends when the player cracks the code or types quit:

Language: Text
$ node guessing_game.mjs
The secret code is a number from 1 to 100
Type quit to stop playing.
Your guess? 50
Try a lower number.
Your guess? abc
Please type a number from 1 to 100
Your guess? 25
Try a higher number.
Your guess? 37
You cracked the code!
$

To get there, you’ll learn how to:

  • Repeat code with while loops
  • Count with for loops
  • Leave a loop early with break
  • Skip the rest of a pass with continue
  • Plan a program before you code it
  • Ask questions in the terminal

By the end, you’ll be able to plan and build a small interactive terminal program that repeats and checks its answers.

You’ll build the game as a script, in small steps that you run as you go, with a secret code that you pick. Along the way, you’ll step through loops and solve coding exercises here on the site, with feedback.

Before you start, you should be able to write functions, make decisions with if and else, and check that an answer is valid, like a number in range.

You should also know where a variable can be used (its scope) and be able to build a small program from helper functions. You’ll work in the VS Code terminal, opened in your course folder. If those skills feel familiar, you’re ready, even if you skipped the earlier courses.

This course comes with sample code and a cheat sheet. The sample code has the files you’ll create in the lessons, plus a starter and a solution for each exercise. Keep the JavaScript cheat sheet open as a quick reference while you work:

Download

Sample Code (.zip)

17.2 KB
Download

JavaScript Cheat Sheet (.pdf)

229.6 KB

Become a Member to join the conversation.