Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to initialize an array with a range of numbers in JavaScript

1 Answer

0 votes
// Demonstrating several ways to build a list containing a range of numbers.
// Each function shows a different style that experienced developers commonly use.

// Build a list using Array.from().
// This is concise, expressive, and uses a built‑in constructor.
function makeRangeArrayFrom(start, end) {
    // Array.from() can take a mapping function that receives the index.
    return Array.from({ length: end - start }, (_, i) => start + i);
}

// Build a list using a simple for‑loop.
// Clear and flexible; works in any environment.
function makeRangeLoop(start, end) {
    const values = [];
    for (let n = start; n < end; n++) {
        values.push(n);
    }
    return values;
}

// Build a list using a generator function.
// Useful when you want lazy iteration or custom stepping.
function* rangeGenerator(start, end) {
    for (let n = start; n < end; n++) {
        yield n;
    }
}

function makeRangeFromGenerator(start, end) {
    return [...rangeGenerator(start, end)];
}

// Build a list using Array.fill() + map.
// Shows how to repurpose an existing array.
function makeRangeFillMap(start, end) {
    return new Array(end - start)
        .fill(0)
        .map((_, i) => start + i);
}

// Print a list for demonstration.
function show(label, values) {
    console.log(`${label}:`, values);
}

function main() {
    const a = makeRangeArrayFrom(1, 10);
    const b = makeRangeLoop(1, 10);
    const c = makeRangeFromGenerator(1, 10);
    const d = makeRangeFillMap(1, 10);

    show("Array.from()", a);
    show("loop", b);
    show("generator", c);
    show("fill + map", d);
}

main();



/*
run:

Array.from(): [
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]
loop: [
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]
generator: [
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]
fill + map: [
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]

*/

 



answered Aug 18 by avibootz
...