Loops are how you repeat an action without writing the same line of code over and over. JavaScript has several loop types — for, while, and do...while — and printing the numbers from 1 to N is the clearest way to see how each one controls its start, its stop condition, and how it moves forward on every pass.

Using a for Loop

The for loop packs initialization, condition, and increment into one line, which makes it the most common choice when you know in advance how many times you need to repeat something.

const n = 10;

for (let i = 1; i <= n; i++) {
  console.log(i);
}

Output:

1
2
3
4
5
6
7
8
9
10

Here, let i = 1 sets the starting value, i <= n is checked before every pass (the loop stops as soon as it's false), and i++ increases i by 1 after each pass. Changing any of these three parts changes the whole pattern — for example, starting at 0, stopping at i < n, or stepping by i += 2 to print only even numbers.


Using a while Loop

A while loop is a better fit when the number of repetitions isn't known ahead of time — it just keeps going as long as its condition stays true. The logic here is identical to the for loop above, just written differently.

const n = 10;
let i = 1;

while (i <= n) {
  console.log(i);
  i++; // must update manually, or the loop never ends
}

Output:

1
2
3
4
5
6
7
8
9
10

Unlike the for loop, a while loop doesn't force you to update the counter — it's your responsibility to do it inside the loop body. Forgetting the i++ line here would create an infinite loop, since i would stay at 1 forever and the condition would never become false.