Creating Arrays
Arrays in JavaScript are used to store ordered collections of values. They can be created using array literals, the Array constructor, or static methods like Array.from() and Array.of().
Key Points
Section titled “Key Points”- Array literals:
[]with comma‑separated values. Arrayconstructor:new Array(length)ornew Array(elements).Array.of(): creates an array from arguments, avoiding the single‑number special case.Array.from(): creates an array from array‑like or iterable objects.
Code Example
Section titled “Code Example”// Array literalconst fruits = ["apple", "banana", "cherry"];
// Array constructorconst numbers = new Array(5); // empty array with length 5const colors = new Array("red", "blue"); // ["red", "blue"]
// Array.of() – avoids single‑number trapconst arr1 = Array.of(7); // [7]const arr2 = Array.of(1, 2, 3); // [1, 2, 3]
// Array.from() – from string or array-likeconst chars = Array.from("hello"); // ["h", "e", "l", "l", "o"]const fromSet = Array.from(new Set([1, 2, 3])); // [1, 2, 3]