How to Generate Values in A Range in JavaScript

Valentine Kagwiria Feb 02, 2024
  1. Numbers Range in JavaScript
  2. Characters Range in JavaScript
How to Generate Values in A Range in JavaScript

This article explains how to get the range of numbers or characters within specified bounds with JavaScript methods.

Numbers Range in JavaScript

You can use the spread operator to find the range of any numbers between 0 and 1 as follows:

var num = [...Array(9).keys()];
alert(num)

Output:

1,2,3,4,5,6,7,8

Or

var num = Array.from({length: 10}, (x, i) => i);
alert(num)

Output:

0,1,2,3,4,5,6,7,8,9

If you don’t want your range to start at zero, you can specify the start and end numbers as follows.

var num = Array.from({length: 20 - 10}, (f, g) => g + 10);
alert(num)

Output:

10,11,12,13,14,15,16,17,18,19

Remember that in JavaScript, the position of numbers, characters or objects in an array starts at zero. This means that in 1,2,3,4, the number 1 is in position 0, and the number 4 is in position 3. Therefore, if you need to generate the range between one and twenty with 20 inclusive, your upper bound should be 20+1.

Characters Range in JavaScript

var char = String.fromCharCode(
    ...[...Array('F'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(
        i => i + 'A'.charCodeAt(0)));
alert(char)

Output:

ABCDEF