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);new Array(5) creates an array with empty slots, not five explicit undefined values.
const array = new Array(5);console.log(array[0]); // undefinedconsole.log(array); // [ <5 empty items> ]
const sparse = [1, , 3];console.log(sparse); // [1, <1 empty item>, 3]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"];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"]const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]arr.pop(); // removes the last item
arr.unshift(0); // add to the beginningarr.shift(); // remove from the beginning
arr.splice(1, 1, "x"); // modify in placeconst 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);const arr = [10, 20, 30, 40];
arr.includes(20); // truearr.indexOf(30); // 2arr.find((item) => item > 25); // 30arr.findIndex((item) => item > 25); // 2const 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];typeof [] === "object".length can be changed manually.const arr = [1, 2, 3, 4];arr.length = 2;console.log(arr); // [1, 2]const [first, second] = ["a", "b", "c"];const arr1 = [1, 2];const arr2 = [3, 4];const merged = [...arr1, ...arr2];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.