Welcome to the While and Do-While Loop Tutorial!
Hey there, coder! Are you ready to learn about two powerful loop concepts in JavaScript? In this tutorial, we'll explore While and Do-While Loops using a fun example: repeating a game level until the player collects all the coins.
Get Ready to Code!
Open your index.js
file and get ready to write some code!
Problem Statement: Imagine you're creating a game where the player needs to collect all the coins in a level. If the player doesn't collect all the coins, the level restarts. We'll use While and Do-While Loops to achieve this.
While Loop: A While Loop runs as long as a certain condition is true. Let's create a While Loop to repeat the game level until the player collects all the coins.
Task 1: Create a While Loop
In your index.js
file, write the following code:
let coinsCollected = 0let totalCoins = 5
while (coinsCollected < totalCoins) { console.log(`You're on level 1. You have collected ${coinsCollected} coins.`) coinsCollected++}
console.log(`Congratulations! You've collected all ${totalCoins} coins!`)
Run the Code! Click the "Run" button to execute the code. Observe the console output.
What's Happening:
The While Loop runs as long as coinsCollected
is less than totalCoins
. In each iteration, we increment coinsCollected
by 1. Once coinsCollected
reaches totalCoins
, the loop exits, and we print a success message.
Do-While Loop: A Do-While Loop is similar to a While Loop, but it executes the code block at least once before checking the condition. Let's modify our code to use a Do-While Loop.
Task 2: Create a Do-While Loop Replace the While Loop code with the following Do-While Loop code:
let coinsCollected = 0let totalCoins = 5
do { console.log(`You're on level 1. You have collected ${coinsCollected} coins.`) coinsCollected++} while (coinsCollected < totalCoins)
console.log(`Congratulations! You've collected all ${totalCoins} coins!`)
Run the Code Again! Click the "Run" button to execute the code. Observe the console output.
What's Happening:
The Do-While Loop executes the code block at least once, and then checks the condition. If the condition is true, the loop continues. In our example, the loop runs until coinsCollected
reaches totalCoins
.
Real-World Example: Imagine a game like Super Mario Bros. where Mario needs to collect all the coins in a level to progress. The game would use a While or Do-While Loop to repeat the level until Mario collects all the coins.
You've Learned: Congratulations! You now understand how to use While and Do-While Loops in JavaScript. These loops are essential in game development, but also in various other applications, such as data processing and algorithm implementation.
Next Steps: In the next tutorial, we'll explore Functions in JavaScript. Get ready to learn about reusable code blocks!
Happy Coding!
Tests