0 of 8 problems solved • 0%

Exercise prompt

Trace a while Loop

A while loop checks its condition before each repetition.

Example

let lives = 2; while (lives > 0) { console.log("Lives:", lives); lives -= 1; } // Output: // Lives: 2 // Lives: 1
  • lives > 0 lets the body run while lives is greater than zero.
  • lives -= 1 subtracts 1 each time. At 0, the condition is false and the loop stops.

Without that subtraction, this loop would repeat forever.

Predict the output

A device reports its battery before using one unit. Predict the entire log, including its value when the loop stops.

let battery = 3; while (battery > 0) { console.log("Battery:", battery); battery -= 1; } console.log("Stopped:", battery);
What will this code print?