Array literals `[]` are the standard way to create arrays. **Array.from()** converts any iterable or array-like object to an array (great with `{length: N}` to create sequences). **Array.of()** fixes the quirky `new Array(3)` behavior (creates sparse array of length 3 vs. `Array.of(3)` = `[3]`).
1Understanding Creating Arrays
Array literals [] are the standard way to create arrays. Array.from() converts any iterable or array-like object to an array (great with {length: N} to create sequences). Array.of() fixes the quirky new Array(3) behavior (creates sparse array of length 3 vs. Array.of(3) = [3]).
Avoid 'new Array(n)' — it creates a sparse array of length n, not an array containing n. Use Array.from({length: n}, (_, i) => i) instead.
// Array literal
const fruits = ['apple', 'banana', 'cherry'];
// Array.from with mapping function
const squares = Array.from({ length: 5 }, (_, i) => i ** 2);
console.log(squares); // [0, 1, 4, 9, 16]
// Convert Set to Array
const unique = Array.from(new Set([1, 2, 2, 3, 3]));
console.log(unique); // [1, 2, 3]2Practical Example
Here is a real-world application of Creating Arrays showing how it is used in production JavaScript code.
// Spread to convert iterables
const str = 'hello';
const chars = [...str];
console.log(chars); // ['h','e','l','l','o']
// 2D array (matrix)
const matrix = Array.from({ length: 3 }, () => Array(3).fill(0));
console.log(matrix);3Best Practices
Follow these guidelines when working with Creating Arrays:
1. Use [] literal for most array creation
2. Use Array.from() to convert iterables and NodeLists
3. Use fill() and from() to create initialized arrays
Tip: Avoid 'new Array(n)' — it creates a sparse array of length n, not an array containing n. Use Array.from({length: n}, (_, i) => i) instead.
// Array literal
const fruits = ['apple', 'banana', 'cherry'];
// Array.from with mapping function
const squares = Array.from({ length: 5 }, (_, i) => i ** 2);
console.log(squares); // [0, 1, 4, 9, 16]
// Convert Set to Array
const unique = Array.from(new Set([1, 2, 2, 3, 3]));
console.log(unique); // [1, 2, 3]