How to use For…in loop method In Javascript
Using a for…in loop, we iterate through the indices of an array-like object, performing a specific action for each index. It’s often used to traverse object properties but can be adapted for other tasks like generating sequences.
Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}
Example: In this example, we will use For..in loop to generate numbers in the given range.
function generateNumber(num1, num2) {
const result = [];
for (let i in [...Array(num2 - num1 + 1)]) {
result.push(Number(i) + num1);
}
return result;
}
const result = generateNumber(1, 8);
console.log(result);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
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