• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking
○Declaring Variables○let and const in Practice○Operators○Type Conversion
○Conditionals○Switch Statement○For Loops●While Loop○Break and Continue
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions
○Arrays○Array Mutation Methods○Array Search and Slice○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every
○Objects○Object Methods and Destructuring○JSON○Math and Date○Date Basics
○02 Template Literals○String Methods○Regular Expressions
○Higher-Order Functions○Callbacks○map, filter, and reduce○Recursion○Project - Data Transform Pipeline
○OOP Introduction○Classes○Inheritance○Encapsulation
○Asynchronous JavaScript○Promises and Async Await○Async API Simulation

While Loop

Use while when you do not know ahead of time how many iterations you need.

while loop

javascript
let count = 0;
while (count < 5) {
    console.log(count);
    count++;
}

The condition is checked before each iteration. If count starts at 5, the loop body never runs.

do...while loop

The condition is checked after each iteration — so the body always runs at least once:

javascript
let num = 0;
do {
    console.log(num);
    num++;
} while (num < 3);

Your Task

  1. Write a function countdown(n) that returns an array containing numbers from n down to 1, using a while loop. For example, countdown(5) → [5, 4, 3, 2, 1].
  2. Write a function collatz(n) that returns the number of steps to reach 1 using the Collatz sequence:
    • If n is even: n = n / 2
    • If n is odd: n = 3 * n + 1
  3. Display in #output: "Countdown from 5: 5,4,3,2,1".
Hint 1
1 / 3
HINT 1

A while loop keeps running as long as its condition is true.

Loading editor…
READY
intercourses
javascript