An array stores an ordered group of values. JavaScript arrays can mix value types, although keeping related values together usually makes code easier to understand. Arrays can grow and shrink with methods such as push() and pop().
Creating arrays
Use square brackets when the values are known. Array(n).fill(0) creates n slots and fills each one with zero.
let scores = [88, 91, 76, 95, 83];
let counts = Array(4).fill(0);
counts[0] = 12;
counts[1] = 9;Array(4).fill(0) contains four zeroes because fill(0) explicitly supplies that value. Array(4) alone contains four empty slots.
KNOWLEDGE QUIZ
Accessing array elements
Array indexes start at 0, so the first element is scores[0]. An array of length 5 has indexes 0 through 4. Reading scores[5] produces undefined; it does not add a new element.
let scores = [88, 91, 76, 95, 83];
console.log(scores[0]); // 88
console.log(scores[4]); // 83
scores[2] = 80;
console.log(scores[2]); // 80Array index spotlight
Select any slot and let a JavaScript expression point to exactly one value. Valid indexes always run from 0 through scores.length - 1.
KNOWLEDGE QUIZ
Array length and loops
Arrays use the length property without parentheses. The last valid index is array.length - 1. Use an index loop when positions matter and for...of when only values matter.
for (let i = 0; i < scores.length; i++) {
console.log(`scores[${i}] = ${scores[i]}`);
}
for (const score of scores) {
console.log(score);
}KNOWLEDGE QUIZ
Common operations
You can rewrite elements, search with a loop, append with push(), and remove the last element with pop().
let values = [4, 0, 7, 0, 2, 9];
values[2] = 5;
for (const value of values) {
console.log(value + " ");
}KNOWLEDGE QUIZ
Move zeroes to the end of an array
- Scan every element with a read index.
- Use a write index for the next nonzero destination.
- Fill the remaining cells with zero after the scan.
Reverse an integer array in place
Use two indexes, left and right, moving inward while swapping values. Transform {2, 4, 6, 8, 10} into {10, 8, 6, 4, 2}.
- Point left at the first element and right at the last.
- Swap both ends, then move both indexes inward.
- Stop when left is no longer less than right and print the array.