How to use while Loop In Javascript
The while loop is another method for iterating over a sequence of values, executing a block of code as long as a specified condition is true. This approach can be particularly useful for generating sequences when the end condition is not known beforehand.
Example: In this example, we will use a while loop to generate both numbers and characters in the specified range.
// Generating a range of numbers using while loop
function generateNumbersWhile(start, end) {
const numbers = [];
let current = start;
while (current <= end) {
numbers.push(current);
current++;
}
return numbers;
}
const numbers = generateNumbersWhile(1, 8);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
// Generating a range of characters using while loop
function generateCharactersWhile(startChar, endChar) {
const characters = [];
let currentCharCode = startChar.charCodeAt(0);
const endCharCode = endChar.charCodeAt(0);
while (currentCharCode <= endCharCode) {
characters.push(String.fromCharCode(currentCharCode));
currentCharCode++;
}
return characters;
}
const characters = generateCharactersWhile('A', 'G');
console.log(characters); // Output: ['A', 'B', 'C', 'D', 'E', 'F', 'G']
Output
[ 1, 2, 3, 4, 5, 6, 7, 8 ] [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ]
JavaScript Program to Generate a Range of Numbers and Characters
Generating a range of numbers and characters means creating a sequential series of numerical values or characters, typically within specified start and end points, forming a continuous sequence or collection.
Contact Us