Returning array of natural numbers between a range in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of two numbers [a, b] (a <= b), specifying a range.

Our function should return an array of all natural numbers between a and b including them

Example

Following is the code −

 Live Demo

const range = [6, 45];
const naturalBetweenRange = ([lower, upper] = [1, 1]) => {
   if(lower > upper){
      return [];
   };
   const res = [];
   for(let i = lower; i <= upper; i++){
      res.push(i);
   };
   return res;
};
console.log(naturalBetweenRange(range));

Output

[ 6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45 ]
raja
Published on 17-Apr-2021 16:54:23
Advertisements