Arrays

Updated · 7 min read
mediumES2026javascriptarrayslengthreference

An array in JavaScript is an ordered list of values, stored under one name and accessed by position (its index). Arrays hold the Fee Tracker's lists: students, payments, fees per grade. Unlike arrays in Java or C, a JavaScript array can grow and shrink at any time and can hold values of different types. Under the surface, an array is a special kind of object, which explains how copying and comparing them work.

In One Minute

  • Create arrays with square brackets: const fees = [120, 85, 45];.
  • Items are numbered from 0. fees[0] is the first item, fees.at(-1) the last.
  • length is one more than the highest index; setting it shorter truncates the array.
  • Arrays are objects: typeof says "object", Array.isArray says true, and variables hold a reference.
  • A const array can still change its items; const only stops reassignment.

Creating Arrays

Syntax

syntax.js
const name = [item0, item1, item2];

Example

create.js▶ Try it
const students = ["Navika", "Srihitha", "Advitha"];
const fees = [120, 85, 45];
const mixed = ["Navika", 9, true, null, { city: "Dallas" }, [1, 2]];
const empty = [];
 
console.log(students);
console.log(fees.length, empty.length);
console.log(mixed);
Output
['Navika', 'Srihitha', 'Advitha']
3 0
['Navika', 9, true, null, { city: 'Dallas' }, [1, 2]]

Mixing types is allowed, but real arrays usually hold one kind of thing (all names, or all payment objects). That makes them easier to loop over and lets the engine store them efficiently.

Other Ways to Create Arrays

CodeResultUse it for
[1, 2, 3][1, 2, 3]Almost always
Array.of(7)[7]One item that is a number
Array.from("abc")['a', 'b', 'c']Turning an iterable into an array
Array.from({ length: 3 }, (_, i) => i * 10)[0, 10, 20]Generating values
new Array(3).fill(0)[0, 0, 0]A fixed number of identical items
new Array(3)3 empty slotsAvoid: creates holes (see below)
from.js▶ Try it
console.log(Array.from({ length: 4 }, (_, i) => 9 + i));
console.log(Array.from("Fee"));
console.log(new Array(3).fill(0));
console.log(new Array(3, 4));
Output
[9, 10, 11, 12]
['F', 'e', 'e']
[0, 0, 0]
[3, 4]

new Array(3) makes three empty slots, but new Array(3, 4) makes an array holding 3 and 4. That inconsistency is why Array.of and literals are preferred.

Reading and Changing Items

index.js▶ Try it
const fees = [120, 85, 45];
 
console.log(fees[0]);
console.log(fees[fees.length - 1]);
console.log(fees.at(-1));
console.log(fees[10]);
 
fees[1] = 90;
fees[3] = 200;
console.log(fees, fees.length);
Output
120
45
45
undefined
[120, 90, 45, 200] 4

Explanation: reading an index that doesn't exist gives undefined, not an error. Assigning to fees[3] (one past the end) adds an item and grows the array. at() accepts negative indexes, counting from the end.

The length Property

length is always one more than the highest index. It isn't a count of items you put in; it is a property you can also set:

length.js▶ Try it
const items = ["tuition", "books", "lab", "uniform"];
 
items.length = 2;
console.log(items);
 
items.length = 0;
console.log(items);
Output
['tuition', 'books']
[]

Setting length smaller deletes everything past it. items.length = 0 is a quick way to empty an array in place, which affects every variable that refers to it.

Holes and Sparse Arrays

Assigning far past the end leaves holes: indexes with no value at all:

holes.js▶ Try it
const fees = [120];
fees[3] = 45;
 
console.log(fees.length);
console.log(fees[1]);
console.log(1 in fees);
 
let count = 0;
fees.forEach(() => count++);
console.log(count);
Output
4
undefined
false
2

Explanation: the array has a length of 4 but only two real items. Reading a hole gives undefined, but 1 in fees shows the index doesn't exist, and forEach skips holes entirely. Arrays with holes are called sparse; they behave inconsistently across methods and are slower. Avoid them: use push to add items.

Arrays Are Objects

An array is an object whose keys are the indexes (as strings) plus a special length. That has three consequences:

objects.js▶ Try it
const fees = [120, 85];
 
console.log(typeof fees);
console.log(Array.isArray(fees));
 
const sameList = fees;
sameList.push(45);
console.log(fees);
 
console.log([120, 85] === [120, 85]);
Output
object
true
[120, 85, 45]
false
  1. typeof can't detect arrays. Use Array.isArray(value).
  2. Variables hold references. sameList = fees doesn't copy the array; both names point at the same one, so a push through either name is visible through both.
  3. Comparison is by reference. Two arrays with the same contents are different objects, so === is false.

To make a real copy, use spread ([...fees]) or fees.slice(); the destructuring and spread lesson covers copying in depth.

In Practice

The Fee Tracker keeps fees per grade in an array indexed from grade 9, and builds a printable table:

grade-fees.js▶ Try it
const FIRST_GRADE = 9;
const feesByGrade = [400, 415, 430, 445];
 
function feeFor(grade) {
  const fee = feesByGrade[grade - FIRST_GRADE];
  return fee ?? null;
}
 
console.log(feeFor(9), feeFor(12), feeFor(8));
 
for (let i = 0; i < feesByGrade.length; i++) {
  console.log(`Grade ${FIRST_GRADE + i}: $${feesByGrade[i]}`);
}
console.log("Highest:", feesByGrade.at(-1));
Output
400 445 null
Grade 9: $400
Grade 10: $415
Grade 11: $430
Grade 12: $445
Highest: 445

Common Mistakes

Off by one with the last item. arr[arr.length] is undefined. Use arr[arr.length - 1] or arr.at(-1).

Thinking assignment copies. const copy = original shares the array. Use [...original].

Checking for an array with typeof. It says "object". Use Array.isArray.

Comparing arrays with ===. It compares references. Compare items, or for simple values a.length === b.length && a.every((x, i) => x === b[i]).

Under the Hood

V8 doesn't store every array the same way. It tracks an elements kind for each array and picks the most compact representation that fits: PACKED_SMI_ELEMENTS for small integers with no holes, PACKED_DOUBLE_ELEMENTS for numbers, PACKED_ELEMENTS for anything else, and HOLEY_ versions of each once a hole appears. Transitions only go one way, toward more general kinds: once an array has held a string or had a hole, it never goes back to the faster form, even if you fix the data. Very sparse arrays (such as one item at index 1,000,000) switch to dictionary mode, a slow hash table.

The practical rules that follow: create arrays with their final items (or push into them), keep one type of value per array, and never leave holes. You'll rarely notice the difference in small scripts, but it matters in loops over large data.

Interview Corner

How do you check whether a value is an array?

Array.isArray(value). typeof returns "object" for arrays, and instanceof Array fails for arrays created in another global environment (an iframe, or a different Node.js vm context).

What happens when you set an array's length to a smaller number?

The array is truncated in place: elements at indexes greater than or equal to the new length are deleted. Setting length = 0 empties the array for every reference to it, unlike arr = [], which only rebinds one variable.

What does this print?

Show solution
puzzle.js▶ Try it
const a = [1, 2, 3];
const b = a;
b.length = 1;
const c = [, 5];
console.log(a, c.length, 0 in c);
Output
[1] 2 false

a and b are the same array, so truncating through b shortens a. [, 5] has a hole at index 0: length 2, but index 0 doesn't exist.

Practice

Challenge: Write lastN(arr, n) that returns a new array with the last n items of arr (or all of them if there are fewer), without changing arr.

Show solution
last-n.js▶ Try it
function lastN(arr, n) {
  return arr.slice(Math.max(arr.length - n, 0));
}
 
const fees = [120, 85, 45, 200];
console.log(lastN(fees, 2));
console.log(lastN(fees, 10));
console.log(fees);
Output
[45, 200]
[120, 85, 45, 200]
[120, 85, 45, 200]

Quick check: Arrays

3 questions
1What does ["a", "b", "c"].at(-1) return?
2What does typeof [] return?
3After const b = a; b.push(1), what happens to a?

Key Takeaways

TaskCode
Createconst a = [1, 2, 3];
GenerateArray.from({ length: n }, (_, i) => i)
First / lasta[0], a.at(-1)
Is it an array?Array.isArray(a)
Copy[...a]
Empty in placea.length = 0

Was this tutorial helpful?

Lesson 31 of 139