Ask Your Question
4

Is there a JavaScript function similar to "range()" that can produce a series of values between given limits?

asked 2023-06-30 21:46:30 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-30 22:00:02 +0000

bukephalos gravatar image

No, JavaScript does not have a built-in function called "range()" that can produce a series of values between given limits. However, you can easily create a function that can achieve this functionality. Here's an example:

function range(start, end, step = 1) {
  const result = [];
  for (let i = start; i <= end; i += step) {
    result.push(i);
  }
  return result;
}

// Example usage:
console.log(range(1, 5)); // [1, 2, 3, 4, 5]
console.log(range(0, 10, 2)); // [0, 2, 4, 6, 8, 10]
console.log(range(5, 1)); // []

In this example, the range() function takes three parameters: start and end specify the limits of the range, and step specifies the increment between values (defaulting to 1 if not specified). The function initializes an empty array called result, then uses a for loop to iterate from start to end in increments of step, pushing each value into result. Finally, the function returns the populated result array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-30 21:46:30 +0000

Seen: 9 times

Last updated: Jun 30 '23