Have you ever worked on a problem where you needed to make a list of all the numbers between two inputs and manipulate them in some sort of way? Recently, I found myself in just this predicament and thought that JavaScript would have a nice and easy built in function to make the process easier, like Ruby does. I was surprised to find that there is nothing similar to the simple built in Ruby Range method, and quite a bit of different ways to accomplish this in JavaScript.

In Ruby, you can build a new array from ranges by using the built in method .to_a or the Array method. If we need to create a range of years from 2010 to 2020, you would do it like (2010..2020).to_a or Array (2010..2020) . Inside the parenthesis we are giving Ruby two numbers and two dots, which Ruby interprets as creating an inclusive range from 2010 to 2020.

Image for post

As seen above, and inclusive range creates an array for of all the numbers between and including the ones that invoked it.

Ruby also allows us to call the same two methods with three dots, which would create a new array that would exclude the specified highest value.

Image for post

Calling our range method with three dots 2010...2020 creates an array for all the numbers from 2010–2019, and does not include 2020. As you can see, very easy and simple to create a range with specified parameters. In Ruby, the range functionality doesn’t only stop at numbers! Letters, conditionals, and even intervals can all use the built in range methods to produce some easy to read and compute functionality in our code.

Image for post


Now, back to our JavaScript range issue. JavaScript does not have a two/three dot notation for creating ranges, however we could use the Ruby examples and create our own. In Ruby, the .to_a and the Array methods are built-in methods for creating new Arrays. So our JavaScript code could use the same foundation, and create a new Array to store all our numbers in. Next, using a for loop, we could loop through the numbers and push them into the array until we reach our higher number and break the loop.

Image for post

If we wanted to make our JavaScript code act like a Ruby exclusive range, our second argument in the for loop would change to i < 2020. While this is great, our use for continuously returning a range from 2010 to 2020 is rather limited. Our next change would be to write this to accept arguments, so that the code could perform a variety of tasks, and not just for this past decade. Writing this to be more dynamic would involve making a function that takes in two arguments for our range numbers.

#beginners-guide #javascript #python

Creating a Range in JavaScript
2.30 GEEK