Skip to the content

Counting steps

JavaScript · Unit 21: Complexity

You don't need a stopwatch to tell whether a program is fast: you can count how many times it works.

A variable that goes up on every turn tells you.

function steps(n) {
  let s = 0;
  for (let i = 0; i < n; i++) {
    s++;
  }
  return s;
}
console.log(steps(5));

Prints

5

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it so s says how many turns the loop took.

  3. 3. Multiple choice

    If n is 100, how many times does s++ run?

  4. 4. Predict the output

    This loop moves two at a time. What does it print?

  5. 5. Find the bug

    steps(6) should give 6, because the loop takes 6 turns. Which line has the error?

  6. 6. Put the lines in order

    Build a counter that says how many items it went through.

  7. 7. Predict the output

    filter keeps the even ones. How many items did it look at?

  8. 8. Multiple choice

    Why do we count steps instead of measuring the seconds it takes?

  9. 9. Predict the output

    Both ways add up 1 + 2 + … + 20. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →