Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
October 16, 2024
JavaScript does not have a built-in function like PHP’s `range`, but you can easily implement a function to achieve similar functionality. Here’s how you could create a function that generates a range of numbers or characters:
For Numbers
function range(start, end) { const arr = []; for (let i = start; i <= end; i++) { arr.push(i); } return arr; } console.log(range(1, 3)); // [1, 2, 3]
For Characters
function charRange(start, end) { const arr = []; for (let i = start.charCodeAt(0); i <= end.charCodeAt(0); i++) { arr.push(String.fromCharCode(i)); } return arr; } console.log(charRange("A", "C")); // ["A", "B", "C"]
Combined Function
function rangeGeneric(start, end) { const arr = []; if (typeof start === 'number' && typeof end === 'number') { for (let i = start; i <= end; i++) { arr.push(i); } } else if (typeof start === 'string' && typeof end === 'string') { for (let i = start.charCodeAt(0); i <= end.charCodeAt(0); i++) { arr.push(String.fromCharCode(i)); } } return arr; } console.log(rangeGeneric(1, 3)); // [1, 2, 3] console.log(rangeGeneric("A", "C")); // ["A", "B", "C"]