Array
A contiguous, index-based collection of elements stored in a single block of memory.
Syntax
const arr = new Array(length); // or array literal [] Parameters
| Name | Type | Required | Description |
|---|---|---|---|
length | number | No | Optional initial length of the array. If omitted, an empty array is created; elements can be pushed at any time. |
Returns
Array — A new Array instance.
Examples
const nums = [10, 20, 30, 40, 50];
console.log(nums[2]); // random access O(1)
nums.push(60);
console.log(nums.length);
Output
30
6
const sparse = new Array(5).fill(0);
sparse[2] = 99;
console.log(sparse);
Output
[ 0, 0, 99, 0, 0 ]
Notes
| Operation | Best | Avg | Worst | Space |
|---------------|------|------|-------|-------|
| Access by idx | O(1) | O(1) | O(1) | O(n) |
| Search | O(1) | O(n) | O(n) | O(1) |
| Insert (end) | O(1) | O(1) | O(n)* | O(1) |
| Insert (mid) | O(n) | O(n) | O(n) | O(1) |
| Delete (end) | O(1) | O(1) | O(1) | O(1) |
| Delete (mid) | O(n) | O(n) | O(n) | O(1) |
*O(n) worst case for push when internal buffer must be resized.
JavaScript `Array` is dynamic and can hold mixed types. For typed
numeric data prefer `Int32Array` / `Float64Array` (TypedArrays)
which store values in a true contiguous buffer.