Tutorial: How To Create a Range Of Numbers with Underscore.js (includes video)
With Underscore's range function, you can easily generate a range of numbers customized to your liking. You could do the same thing with a basic Javascript for loop, but _.range is a faster and easier to use alternative.
Arguments
Range takes three arguments:
start (optional):
Range is going to create a list of numbers for you. This is where you tell it where to start from. If you want a list of numbers from 0 to 10, your start value would be 0. This is an inclusive value, so whatever number will be included in the range that Underscore returns. If you don't provide a value for start, it will default to 0.
stop
This is where you want your range to stop. Note that unlike start, stop is exclusive so the number you provide for stop won't be included in the returned array of numbers. For example, if you set your stop value to 10, your range will stop at 9.
step (optional):
This value determines how many numbers will be omitted between each number that is included in the returned array. For example, a step value of 1 will count by 1. A step value of 2 will count by 2's, and so on. You can also use a negative step to count backwards.
Examples:
How does it work?
Watch the video below to see me walkthrough the source code for Underscore's range function in the debugger.
Challenge
Write a program that console.logs the old chant we all did as kids after sports games. (Include line breaks).
"2"
"4"
"6"
"8"
"Who do we appreciate?"
Additional thoughts
It would be cool if there was a version of range that would allow a function as the step argument so we could have a dynamic step, allowing us to easily create exponential ranges, fibonacci sequences, etc.