óCoffeeScript Cookbook

Define Ranges Array

Problem

You want to define a range in an array.

Solution

There are two ways to define a range of array elements in CoffeeScript.

# inclusive
myArray = [1..10]
# => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
# exclusive
myArray = [1...10]
# => [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

We can also reverse the range of element by writing it this way.

myLargeArray = [10..1]
# => [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
myLargeArray = [10...1]
# => [ 10, 9, 8, 7, 6, 5, 4, 3, 2 ]

Discussion

Inclusive ranges are defined by the ‘..’ operator and include the last value.

Exclusive ranges are defined by ‘…’, and always omit the last value.