Codiqo

Learn JavaScript · lesson 18 of 60 · about 8 minutes

break, continue and Direction

Make each visitor a handle from their name: go through it letter by letter, skip the spaces with continue, and stop at 8 letters with break.

What you'll learn

  • Count down and in steps
  • Go through text one character at a time
  • Skip with continue and exit early with break

A handle for every visitor

Sam's page gives each visitor a short handle made from their name, like @adalovel for Ada Lovelace: lower case, no spaces, at most 8 letters. Going through a name one letter at a time is a job for a loop, but this loop has to skip the spaces and stop early.

Any direction, any step

The step can be anything: i-- counts down and i += 5 jumps in fives.

Down and in steps

for (let i = 3; i > 0; i--) {
  console.log(i);
}
for (let i = 0; i <= 20; i += 10) {
  console.log(i);
}

Output

3
2
1
0
10
20

Going through text

for (let i = 0; i < text.length; i++) visits every character, and text[i] is the one on this lap. The last index is text.length - 1, so the condition uses <, not <=.

break and continue

break leaves the loop completely. continue skips the rest of this lap and moves on to the next one.

Skipping and stopping

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue;
  if (i > 7) break;
  console.log(i);
}

Output

1
3
5
7

A handle from the visitor's name

const nameText = "Ada Lovelace";
const lower = nameText.toLowerCase();
let handle = "";
for (let i = 0; i < lower.length; i++) {
  if (lower[i] === " ") {
    continue;
  }
  handle += lower[i];
  if (handle.length === 8) {
    break;
  }
}
document.querySelector("#handle").textContent = `Your handle: @${handle}`;

Tip

break only leaves the loop it's in. The code after the loop still runs.

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.