Do More with Less

Now, supposing that we want to count from 10 to 15, we can’t use countToTen or countTo because they both start counting at 1. We could write a new function, countFromTenTo, but that’s not much better. What if we want to start at 11 or 9? What we really want is a function that can count from any number to any number. We’ll call our function countFromXtoY. See Listing 8.13.

Listing 8.13 A Generalized Function for Counting from Any Number to Any Number

function countFromXtoY(x, y) {  for (var i=x; i<=y; i++) {    console.log(i);  }}

Now that is reusable. Now I can use countFromXtoY(10, 15) to count from 10 to 15, or countFromXtoY(300,5000) to count from 300 to 5,000, or countFromXtoY(10, 1) to count ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.