Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Display all the numbers from a range of start and end value in JavaScript?
In JavaScript, you can display all numbers within a specified range using various methods. The most common approach is using a for loop to iterate through the range.
Using for Loop
Here's how to display numbers from a start value to an end value using a for loop:
var startValue = 10;
var endValue = 20;
var result = [];
function printAllValues(start, end) {
for (var i = start; i < end; i++) {
result.push(i);
}
}
printAllValues(startValue, endValue);
console.log(result.join(','));
10,11,12,13,14,15,16,17,18,19
Using while Loop
You can also use a while loop to achieve the same result:
function displayRange(start, end) {
var numbers = [];
var current = start;
while (current < end) {
numbers.push(current);
current++;
}
return numbers;
}
var startValue = 5;
var endValue = 12;
console.log(displayRange(startValue, endValue));
[ 5, 6, 7, 8, 9, 10, 11 ]
Using Array.from() Method
A more modern approach using the Array.from() method:
function createRange(start, end) {
return Array.from({length: end - start}, (_, i) => start + i);
}
var startValue = 15;
var endValue = 22;
var rangeNumbers = createRange(startValue, endValue);
console.log(rangeNumbers);
console.log(rangeNumbers.join(' - '));
[ 15, 16, 17, 18, 19, 20, 21 ] 15 - 16 - 17 - 18 - 19 - 20 - 21
Including End Value
If you want to include the end value in the range, modify the condition:
function displayRangeInclusive(start, end) {
var numbers = [];
for (var i = start; i <= end; i++) {
numbers.push(i);
}
return numbers;
}
console.log(displayRangeInclusive(8, 12));
[ 8, 9, 10, 11, 12 ]
Comparison
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| for loop | Fast | High | All browsers |
| while loop | Fast | High | All browsers |
| Array.from() | Slower | Very High | ES6+ browsers |
Conclusion
The for loop method is the most efficient and widely supported approach for displaying numbers in a range. Use Array.from() for cleaner code when performance isn't critical.
Advertisements
