range()

Last updated: March 02, 2021

PHP and other programming languages have this function built-in but Javascript doesn't. At least for now.

There's actually a proposal to include it. You can see it here.

Description

Creates an array containing a range of elements

const range = (start, end, step = 1) => {
  let output = [];
  if (typeof end === 'undefined') {
    end = start;
    start = 0;
  }
  for (let i = start; i < end; i += step) {
    output.push(i);
  }
  return output;
};

Parameters

start - the starting value of the sequence

end - the last value of the sequence

step - the incremental step used in the sequence and will default to 1 when not specified. Should be of positive number

Return Values

Returns an array of numbers from start to end

Usage

You can pass a single number:

range(5); // Result: [0, 1, 2, 3, 4]

You can pass two numbers:

range(3,10); // Result: [3, 4, 5, 6, 7, 8, 9]

You can pass two numbers and a third step number:

range(5,20,2); // Result: [5, 7, 9, 11, 13, 15, 17, 19]
range(-2,16,2); // Result: [-2, 0, 2, 4, 6, 8, 10, 12, 14]

Hey, did you find this shortcode useful? I would appreciate if you could share this to your networks.