JavaScript
arrays
programming
code snippets
integer range

Tersest way to create an array of integers from 1..20 in JavaScript

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Creating an array of integers from 1 to 20 in JavaScript has several concise patterns, but readability and compatibility should guide your choice. Modern syntax (Array.from, spread + keys) is expressive and avoids mutation-heavy loops. For older environments, a basic loop may still be clearer and more portable.

This article compares terse and practical approaches, including inclusive range helpers.

Core Sections

1. Array.from with mapping (common modern choice)

javascript
const arr = Array.from({ length: 20 }, (_, i) => i + 1);
console.log(arr); // [1,2,...,20]

Concise, readable, and widely used.

2. Spread + keys() pattern

javascript
const arr = [...Array(20).keys()].map(i => i + 1);

Works, but slightly less direct than Array.from.

3. Reusable range helper

javascript
1const range = (start, end) =>
2  Array.from({ length: end - start + 1 }, (_, i) => start + i);
3
4const arr = range(1, 20);

Best when ranges are used frequently across code.

4. Imperative loop (still valid)

javascript
const arr = [];
for (let i = 1; i <= 20; i++) arr.push(i);

Verbose but crystal clear and easy to debug.

5. Typed arrays when numeric memory layout matters

javascript
const arr = Int32Array.from({ length: 20 }, (_, i) => i + 1);

Useful for numeric workloads needing typed buffer semantics.

6. Performance notes

For small ranges, performance differences are negligible. Prefer maintainability unless this is inside a hot path measured by profiling.

text
choose clarity first, optimize after measurement

Common Pitfalls

  • Off-by-one mistakes (length: 20 but starting at 0 unintentionally).
  • Using terse one-liners that reduce readability for team members.
  • Recomputing ranges repeatedly inside tight loops without caching.
  • Assuming typed arrays behave exactly like normal arrays.
  • Forgetting compatibility constraints in older JS runtimes.

Summary

The tersest practical pattern for [1..20] is usually Array.from({length:20}, (_, i) => i + 1). For repeated use, wrap this in a range helper. Keep code readable, watch off-by-one boundaries, and use typed arrays only when your numeric workload specifically benefits from them.

For long-term maintainability, treat tersest way to create an array of integers from 120 in javascript as a contract problem as much as a code problem. Write down the assumptions that are currently implicit in helper methods, controller glue, and data adapters. Typical assumptions include input normalization rules, default values, acceptable error states, ordering guarantees, and version compatibility boundaries. Once these are explicit, convert them into fast executable checks. Keep one focused smoke test for the core path and one for each high-impact edge case observed in production logs. This style of regression coverage is usually more valuable than large numbers of shallow unit tests because it reflects real failure modes and protects the exact integration seams where breakages usually occur after upgrades.

Operationally, instrument the decision points, not just the final failures. Emit structured diagnostic fields for environment, dependency version, and branch outcome while redacting sensitive values. During incident review, add one permanent guard per root cause: either a targeted test, a validation rule at the boundary, or an alert on unexpected state transitions. Avoid scattering near-identical logic in multiple modules; centralize shared behavior and expose it through a small, documented API so call sites stay consistent. Before rolling out dependency updates, run a compatibility checklist that includes this topic’s smoke tests against representative fixtures. Teams that combine explicit contracts, narrow regression tests, and lightweight telemetry usually see lower incident recurrence and faster mean time to diagnosis.

Documenting one canonical example command or snippet in team docs alongside expected output also reduces future ambiguity, especially when debugging under time pressure.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.