Creating Arrays
Creating Arrays
Section titled “Creating Arrays”Introduction
Section titled “Introduction”JavaScript offers multiple ways to create arrays: literals, constructors, Array.from(), and Array.of().
Array Literal (Recommended)
Section titled “Array Literal (Recommended)”const fruits = ['apple', 'banana', 'orange'];const mixed = [1, 'hello', true, null];const empty = [];const nested = [[1, 2], [3, 4]];Array Constructor
Section titled “Array Constructor”const arr = new Array(5); // Creates array of length 5 (empty slots)const arr2 = new Array(1, 2, 3); // [1, 2, 3]Array.from()
Section titled “Array.from()”// From iterableArray.from('hello'); // ['h', 'e', 'l', 'l', 'o']
// From array-like (with map function)Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]Array.of()
Section titled “Array.of()”Array.of(5); // [5] — unlike new Array(5)Array.of(1, 2); // [1, 2]Summary
Section titled “Summary”- Use array literals
[]for most cases Array.from()for converting iterablesArray.of()to avoid constructor ambiguity