Back to Blog

Node.js While Loops Tutorial | JavaScript Loops for Beginners (2026)

Sandy LaneSandy Lane

Video: Node.js While Loops Tutorial | JavaScript Loops for Beginners (2026) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Node.js While Loops Tutorial | JavaScript Loops for Beginners

Learn how to use while loops in Node.js by creating simple, practical examples like counting up and building a countdown timer. This tutorial covers setting up a Node.js project and writing loops that run based on a condition, helping you understand loop control and variable updates.

Code

// Basic While Loop: counts from 1 to 5
let count = 1;
while (count <= 5) {
  console.log(count);  // Print current count
  count++;            // Increment count by 1
}

// Countdown Timer: counts down from 5 to 1, then prints "Blast off!"
let seconds = 5;
while (seconds > 0) {
  console.log(seconds + '...');  // Print current seconds with dots
  seconds--;                    // Decrement seconds by 1
}
console.log('Blast off!');

Key Points

  • While loops repeatedly execute code as long as the specified condition remains true.
  • Always update the loop variable inside the loop to avoid infinite loops.
  • Use count++ to increment and count-- to decrement loop counters.
  • Node.js projects can be quickly set up with npm init -y to manage your JavaScript code.
  • Practical loops like countdown timers demonstrate real-world uses of while loops in JavaScript.