How to work with an array
You can create an array in JavaScript in several ways, and each one fits different cases.
1. With an array literal (the most common and simplest way)
javascript
const fruits = ["apple", "banana", "cherry"];-
The elements go inside square brackets
[]. -
This is the fastest and most readable way.
-
You can store values of different types:
javascriptconst mixed = [1, "text", true, { name: "Tim" }, [10, 20]];
2. With the new Array() constructor
javascript
const numbers = new Array(1, 2, 3);But there is a nuance:
javascript
const arr = new Array(5);
console.log(arr); // [ <5 empty items> ]If you pass a single argument that is a number, it creates an empty array with length 5, not [5].
To create [5], you need to do this:
javascript
const arr = [5];3. Creating an empty array
javascript
const empty = [];You can add elements later:
javascript
empty.push("apple");
empty.push("banana");
console.log(empty); // ["apple", "banana"]4. Creating an array from another object
From a string
javascript
const letters = Array.from("hello");
console.log(letters); // ['h', 'e', 'l', 'l', 'o']From a set (Set)
javascript
const set = new Set([1, 2, 3]);
const arr = Array.from(set); // [1, 2, 3]From an array-like object (for example, arguments or NodeList)
javascript
function example() {
const args = Array.from(arguments);
console.log(args);
}
example(1, 2, 3); // [1, 2, 3]5. With the Array.of() method
Creates an array from any arguments, even a single number:
javascript
const arr = Array.of(5); // [5]
const arr2 = Array.of(1, 2, 3); // [1, 2, 3]In short:
| Way | Example | Features |
|---|---|---|
| Literal | [] or [1, 2] | the simplest and safest |
new Array() | new Array(3) | creates an array of length 3, if 1 argument |
Array.of() | Array.of(3) | creates [3], without confusion |
Array.from() | Array.from("abc") | turns iterable objects into an array |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.