1. Creating Arrays

In JavaScript, an Array is technically an object, so there are two common ways to create one:

const numbers = new Array(1, 2, 3, 4, 5);
const fruits = ["apple", "blueberry", "orange"];
const arr1 = [];
const arr2 = new Array(5);

About empty slots

new Array(5) creates an array with empty slots, not five explicit undefined values.

const array = new Array(5);
console.log(array[0]); // undefined
console.log(array); // [ <5 empty items> ]
const sparse = [1, , 3];
console.log(sparse); // [1, <1 empty item>, 3]

Characteristics

JavaScript arrays are closer to Python lists than to low-level fixed-type arrays. They are dynamic and can hold values of different types.

const arr = [1, "hello", 3.14, { name: "Tom" }, () => "ok"];

2. Accessing and Updating Arrays

Use indexes to read or write values:

const arr = ["a", "b", "c"];
console.log(arr[0]); // "a"
arr[1] = "beta";
arr[3] = "delta";
console.log(arr); // ["a", "beta", "c", "delta"]

3. Common Methods

3.1 Add and remove

const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // removes the last item
arr.unshift(0); // add to the beginning
arr.shift(); // remove from the beginning
arr.splice(1, 1, "x"); // modify in place

3.2 Iteration

const arr = [1, 2, 3];
arr.forEach((item) => console.log(item));
const doubled = arr.map((item) => item * 2);
const filtered = arr.filter((item) => item > 1);
const total = arr.reduce((sum, item) => sum + item, 0);

3.3 Search and lookup

const arr = [10, 20, 30, 40];
arr.includes(20); // true
arr.indexOf(30); // 2
arr.find((item) => item > 25); // 30
arr.findIndex((item) => item > 25); // 2

3.4 Convert and merge

const arr = [1, 2, 3];
arr.join(","); // "1,2,3"
arr.slice(1); // [2, 3]
const merged = arr.concat([4, 5]);
const spreadMerged = [...arr, 4, 5];

4. Special Notes

  • Arrays can be sparse.
  • Arrays are objects: typeof [] === "object".
  • length can be changed manually.
const arr = [1, 2, 3, 4];
arr.length = 2;
console.log(arr); // [1, 2]

5. Advanced Usage

Destructuring

const [first, second] = ["a", "b", "c"];

Spread syntax

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];

Combining arrays with objects

const users = [
{ id: 1, name: "Tom" },
{ id: 2, name: "Alice" },
];
const names = users.map((user) => user.name);

Arrays are one of the most important JavaScript data structures. The key is not just knowing syntax, but knowing which method fits which job.