In PHP, you can easily create an array of sequential values using the ‘range()’ function, such as:
range(1, 5); // Output: Array(1, 2, 3, 4, 5)
range('X', 'Z'); // Output: Array('X', 'Y', 'Z')
This function facilitates generating numbers and letters between given bounds. Does JavaScript offer a similar feature natively? If it doesn't, what would be an effective way to create such a function manually?
JavaScript does not provide a built-in function exactly like PHP’s range(). However, you can create a custom utility function to achieve the same goal. A simple approach I often use involves a loop to fill an array. Here’s an example for numeric ranges:
function range(start, end) {
const array = [];
for (let i = start; i <= end; i++) {
array.push(i);
}
return array;
}
For character ranges, you can follow a similar principle, converting characters to ASCII values with charCodeAt(), loop over it, and convert back to characters using String.fromCharCode().
You could also use ES6 Array.from to create a range. Like this:
const range = (start, end) => Array.from({length: end - start + 1}, (_, i) => i + start);
Works great for numbers & keeps code clean. handy trick, I use it a lot!