Hey folks, I’m wondering if JavaScript has something similar to Python’s range() function. I want to create a sequence of numbers or letters easily.
In Python, you can do this:
list(range(1, 4)) # [1, 2, 3]
And for letters:
[chr(i) for i in range(ord('A'), ord('D'))] # ['A', 'B', 'C']
Is there a quick way to do this in JavaScript without writing a custom function? If not, what’s the best way to create such sequences? I’m new to JS and would appreciate any tips or tricks. Thanks!
JavaScript doesn’t have a built-in range() function like Python, but there are workarounds. One approach I’ve found useful is using Array.from() with a mapping function:
Array.from({length: 3}, (_, i) => i + 1) // [1, 2, 3]
For letter sequences, you can combine charCodeAt() and String.fromCharCode():
let start = ‘A’.charCodeAt(0);
let end = ‘D’.charCodeAt(0);
Array.from({length: end - start}, (_, i) => String.fromCharCode(start + i))
This produces [‘A’, ‘B’, ‘C’]. It’s not as straightforward as Python, but it’s efficient once you get used to it. These methods can be wrapped in custom functions for reusability if you find yourself needing them often.
yo, js doesn’t have a built-in range() like python, but u can use Array.from() for a quick fix. Like this:
Array.from({length: 3}, (_, i) => i + 1) // [1, 2, 3]
for letters, it’s a bit trickier, but still doable. hope this helps!
JavaScript doesn’t have a built-in range() function like Python, but there are some neat workarounds. I’ve found Array.from() to be pretty handy for creating number sequences:
Array.from({length: 3}, (_, i) => i + 1) // gives [1, 2, 3]
For letter sequences, it’s a bit trickier. I usually go with something like this:
let start = ‘A’.charCodeAt(0);
let end = ‘D’.charCodeAt(0);
Array.from({length: end - start}, (_, i) => String.fromCharCode(start + i))
This gives you [‘A’, ‘B’, ‘C’]. It’s not as straightforward as Python, but it gets the job done. Hope this helps!