Creating arrays in JavaScript can be done in several ways: array literal []
(recommended), constructor new Array()
, Array.of()
, Array.from()
, methods split()
, map()
, filter()
and others. The most popular and recommended way is using array literal.
Main methods:
[]
— array literal (recommended)new Array()
— array constructorArray.of()
— creation from elementsArray.from()
— creation from iterable objectsArray creation is the process of initializing a new data structure that can store an ordered collection of elements. In JavaScript arrays are objects with numeric indexes and special methods.
// Different tasks require different approaches
const empty = []; // Empty array
const withData = [1, 2, 3]; // With data
const fromString = "hello".split(""); // From string
const range = Array.from({length: 5}, (_, i) => i); // Range
console.log(empty); // []
console.log(withData); // [1, 2, 3]
console.log(fromString); // ['h', 'e', 'l', 'l', 'o']
console.log(range); // [0, 1, 2, 3, 4]
// Empty array
const empty = [];
// With elements
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null, {name: "John"}];
// Multidimensional arrays
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// With computed values
const calculated = [2 + 2, Math.PI, new Date()];
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(mixed); // [1, "hello", true, null, {name: "John"}]
Advantages:
Disadvantages:
// Empty array
const empty = new Array();
// Array of specific length
const withLength = new Array(5); // [empty × 5]
// With elements
const withElements = new Array(1, 2, 3, 4, 5);
// Be careful with single numeric argument!
const surprise = new Array(3); // [empty × 3], not [3]!
const expected = new Array("3"); // ["3"]
console.log(withLength); // [undefined, undefined, undefined, undefined, undefined]
console.log(withElements); // [1, 2, 3, 4, 5]
console.log(surprise.length); // 3
console.log(expected); // ["3"]
Advantages:
Disadvantages:
// Creating array from arguments
const numbers = Array.of(1, 2, 3, 4, 5);
const single = Array.of(3); // [3], not array of length 3!
const mixed = Array.of("hello", 42, true, null);
// Comparison with new Array()
console.log(new Array(3)); // [empty × 3]
console.log(Array.of(3)); // [3]
// Useful for creating arrays from variables
function createArray(...args) {
return Array.of(...args);
}
console.log(createArray(1, 2, 3)); // [1, 2, 3]
Advantages:
new Array()
problem with single argumentDisadvantages:
// From string
const fromString = Array.from("hello");
console.log(fromString); // ['h', 'e', 'l', 'l', 'o']
// From Set
const fromSet = Array.from(new Set([1, 2, 2, 3, 3]));
console.log(fromSet); // [1, 2, 3]
// From NodeList
const elements = document.querySelectorAll('div');
const elementsArray = Array.from(elements);
// With transformation function
const doubled = Array.from([1, 2, 3], x => x * 2);
console.log(doubled); // [2, 4, 6]
// Creating range
const range = Array.from({length: 5}, (_, i) => i + 1);
console.log(range); // [1, 2, 3, 4, 5]
// Creating array with repeating values
const repeated = Array.from({length: 3}, () => "hello");
console.log(repeated); // ["hello", "hello", "hello"]
Advantages:
Disadvantages:
// split() - string splitting
const words = "hello world javascript".split(" ");
console.log(words); // ["hello", "world", "javascript"]
const chars = "abc".split("");
console.log(chars); // ["a", "b", "c"]
// match() - finding matches
const numbers = "123-456-789".match(/\d+/g);
console.log(numbers); // ["123", "456", "789"]
// String destructuring
const [...letters] = "hello";
console.log(letters); // ['h', 'e', 'l', 'l', 'o']
// map() - transformation
const original = [1, 2, 3];
const doubled = original.map(x => x * 2);
console.log(doubled); // [2, 4, 6]
// filter() - filtering
const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter(x => x % 2 === 0);
console.log(even); // [2, 4, 6]
// slice() - copying part
const source = [1, 2, 3, 4, 5];
const copy = source.slice(); // Full copy
const part = source.slice(1, 4); // [2, 3, 4]
// concat() - concatenation
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4]
// Copying array
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]
// Combining arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4]
// Adding elements
const base = [2, 3];
const extended = [1, ...base, 4, 5];
console.log(extended); // [1, 2, 3, 4, 5]
// From iterable objects
const fromSet = [...new Set([1, 2, 2, 3])];
console.log(fromSet); // [1, 2, 3]
const fromString = [..."hello"];
console.log(fromString); // ['h', 'e', 'l', 'l', 'o']
function performanceTest() {
const iterations = 1000000;
// Test 1: Array literal
console.time('Literal []');
for (let i = 0; i < iterations; i++) {
const arr = [1, 2, 3, 4, 5];
}
console.timeEnd('Literal []');
// Test 2: new Array()
console.time('new Array()');
for (let i = 0; i < iterations; i++) {
const arr = new Array(1, 2, 3, 4, 5);
}
console.timeEnd('new Array()');
// Test 3: Array.of()
console.time('Array.of()');
for (let i = 0; i < iterations; i++) {
const arr = Array.of(1, 2, 3, 4, 5);
}
console.timeEnd('Array.of()');
// Test 4: Array.from()
console.time('Array.from()');
for (let i = 0; i < iterations; i++) {
const arr = Array.from([1, 2, 3, 4, 5]);
}
console.timeEnd('Array.from()');
}
performanceTest();
Method | Time (ms) | Readability | Support |
---|---|---|---|
[] | ~50 | Excellent | All browsers |
new Array() | ~80 | Good | All browsers |
Array.of() | ~120 | Good | ES6+ |
Array.from() | ~200 | Excellent | ES6+ |
class RangeGenerator {
// Simple range
static range(start, end) {
return Array.from(
{length: end - start + 1},
(_, i) => start + i
);
}
// Range with step
static rangeWithStep(start, end, step = 1) {
const length = Math.floor((end - start) / step) + 1;
return Array.from(
{length},
(_, i) => start + i * step
);
}
// Range with function
static rangeWithFunction(length, fn) {
return Array.from({length}, (_, i) => fn(i));
}
}
// Usage
console.log(RangeGenerator.range(1, 5)); // [1, 2, 3, 4, 5]
console.log(RangeGenerator.rangeWithStep(0, 10, 2)); // [0, 2, 4, 6, 8, 10]
console.log(RangeGenerator.rangeWithFunction(5, i => i * i)); // [0, 1, 4, 9, 16]
class MatrixCreator {
// Creating empty matrix
static createEmpty(rows, cols, defaultValue = 0) {
return Array.from(
{length: rows},
() => Array.from({length: cols}, () => defaultValue)
);
}
// Identity matrix
static createIdentity(size) {
return Array.from(
{length: size},
(_, i) => Array.from(
{length: size},
(_, j) => i === j ? 1 : 0
)
);
}
// Matrix with function
static createWithFunction(rows, cols, fn) {
return Array.from(
{length: rows},
(_, i) => Array.from(
{length: cols},
(_, j) => fn(i, j)
)
);
}
}
// Usage
const empty = MatrixCreator.createEmpty(3, 3);
console.log(empty);
// [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
const identity = MatrixCreator.createIdentity(3);
console.log(identity);
// [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
const multiplication = MatrixCreator.createWithFunction(3, 3, (i, j) => i * j);
console.log(multiplication);
// [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
class DataParser {
// CSV parsing
static parseCSV(csvString) {
return csvString
.trim()
.split('\n')
.map(row => row.split(',').map(cell => cell.trim()));
}
// Creating array from object
static objectToArray(obj, keyName = 'key', valueName = 'value') {
return Object.entries(obj).map(([key, value]) => ({
[keyName]: key,
[valueName]: value
}));
}
// Array grouping
static groupBy(array, keyFn) {
const groups = {};
array.forEach(item => {
const key = keyFn(item);
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
});
return groups;
}
}
// Usage
const csv = `name,age,city
John,25,New York
Jane,30,London
Bob,35,Paris`;
const parsed = DataParser.parseCSV(csv);
console.log(parsed);
// [['name', 'age', 'city'], ['John', '25', 'New York'], ...]
const obj = {a: 1, b: 2, c: 3};
const arrayFromObj = DataParser.objectToArray(obj);
console.log(arrayFromObj);
// [{key: 'a', value: 1}, {key: 'b', value: 2}, {key: 'c', value: 3}]
// Create array of numbers from 1 to 10 using three different methods
const method1 = ?;
const method2 = ?;
const method3 = ?;
console.log(method1); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const method1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const method2 = Array.from({length: 10}, (_, i) => i + 1);
const method3 = [...Array(10)].map((_, i) => i + 1);
// What will this code output?
const a = new Array(3);
const b = Array.of(3);
const c = [3];
console.log(a.length);
console.log(b.length);
console.log(c.length);
console.log(a[0]);
console.log(b[0]);
console.log(c[0]);
3, 1, 1, undefined, 3, 3 — new Array(3) creates array of length 3 with empty slots, Array.of(3) and [3] create array with single element 3.
// Create function that creates array
// of repeating values
function repeat(value, times) {
// Your code
}
console.log(repeat("hello", 3)); // ["hello", "hello", "hello"]
console.log(repeat(42, 5)); // [42, 42, 42, 42, 42]
function repeat(value, times) {
return Array.from({length: times}, () => value);
// or
// return new Array(times).fill(value);
// or
// return [...Array(times)].map(() => value);
}
// Typed arrays
function createNumberArray(length: number): number[] {
return Array.from({length}, (_, i) => i + 1);
}
function createTypedArray<T>(length: number, factory: (index: number) => T): T[] {
return Array.from({length}, (_, i) => factory(i));
}
// Usage
const numbers = createNumberArray(5); // number[]
const strings = createTypedArray(3, i => `item-${i}`); // string[]
class AsyncArrayCreator {
// Creating array with async data
static async createFromPromises(promises) {
return Promise.all(promises);
}
// Creating with async function
static async createWithAsyncFunction(length, asyncFn) {
const promises = Array.from({length}, (_, i) => asyncFn(i));
return Promise.all(promises);
}
// Sequential creation
static async createSequentially(length, asyncFn) {
const result = [];
for (let i = 0; i < length; i++) {
result.push(await asyncFn(i));
}
return result;
}
}
// Usage
const urls = ['url1', 'url2', 'url3'];
const promises = urls.map(url => fetch(url));
const responses = await AsyncArrayCreator.createFromPromises(promises);
const data = await AsyncArrayCreator.createWithAsyncFunction(5, async (i) => {
const response = await fetch(`/api/data/${i}`);
return response.json();
});
function* numberGenerator(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
function* fibonacciGenerator(count) {
let a = 0, b = 1;
for (let i = 0; i < count; i++) {
yield a;
[a, b] = [b, a + b];
}
}
// Creating arrays from generators
const numbers = [...numberGenerator(1, 10)];
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const fibonacci = Array.from(fibonacciGenerator(10));
console.log(fibonacci); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
// 1. Use array literal for simple cases
const numbers = [1, 2, 3, 4, 5]; // ✅ Best choice
// 2. Array.from() for transformations and ranges
const range = Array.from({length: 10}, (_, i) => i + 1); // ✅ Excellent
// 3. Spread for copying and combining
const copy = [...original]; // ✅ Modern and readable
const combined = [...arr1, ...arr2]; // ✅ Clear and efficient
// 4. Use typing in TypeScript
function createArray<T>(items: T[]): T[] {
return [...items]; // ✅ Type-safe
}
// 5. Document complex cases
/**
* Creates two-dimensional array (matrix)
* @param {number} rows - Number of rows
* @param {number} cols - Number of columns
* @param {*} defaultValue - Default value
*/
function createMatrix(rows, cols, defaultValue = 0) {
return Array.from(
{length: rows},
() => Array.from({length: cols}, () => defaultValue)
);
}
// ❌ Don't use new Array() with single numeric argument
const bad = new Array(5); // Creates [empty × 5]
const good = Array.from({length: 5}, () => undefined); // ✅ Explicit
// ❌ Don't rely on automatic conversion
const bad = Array("5"); // Can be unexpected
const good = ["5"]; // ✅ Clear and understandable
// ❌ Don't create arrays in loops unnecessarily
for (let i = 0; i < 1000; i++) {
const arr = []; // ❌ Inefficient
// ... work with arr
}
// ✅ Create once, reuse
const arr = [];
for (let i = 0; i < 1000; i++) {
arr.length = 0; // Clear
// ... work with arr
}
// ❌ Don't forget about performance
const bad = Array.from(Array.from(Array.from([1,2,3]))); // Excessive
const good = [1, 2, 3]; // ✅ Simple and fast
// ❌ Problem
function createArray(size) {
return new Array(size); // Creates empty slots!
}
const arr = createArray(3);
console.log(arr); // [empty × 3]
console.log(arr.map(x => 1)); // [empty × 3] - map skips empty slots!
// ✅ Solution
function createArray(size, defaultValue = undefined) {
return Array.from({length: size}, () => defaultValue);
}
const arr = createArray(3, 0);
console.log(arr); // [0, 0, 0]
console.log(arr.map(x => x + 1)); // [1, 1, 1]
// ❌ Problem
const original = [[1, 2], [3, 4]];
const copy = [...original]; // Shallow copy!
copy[0][0] = 999;
console.log(original[0][0]); // 999 - original changed!
// ✅ Solution for deep copying
function deepCopyArray(arr) {
return arr.map(item =>
Array.isArray(item) ? deepCopyArray(item) : item
);
}
const original = [[1, 2], [3, 4]];
const copy = deepCopyArray(original);
copy[0][0] = 999;
console.log(original[0][0]); // 1 - original unchanged
// ❌ Problem - creating large arrays inefficiently
function createLargeArray() {
const arr = [];
for (let i = 0; i < 1000000; i++) {
arr.push(i); // Many push operations
}
return arr;
}
// ✅ Solution - pre-allocate memory
function createLargeArray() {
return Array.from({length: 1000000}, (_, i) => i);
}
// ✅ Or use typed arrays for numbers
function createLargeNumberArray() {
const arr = new Int32Array(1000000);
for (let i = 0; i < arr.length; i++) {
arr[i] = i;
}
return arr;
}
Array creation is a fundamental operation in JavaScript with multiple approaches:
Main methods:
[]
— fastest and most readablenew Array()
— for arrays of specific lengthArray.of()
— predictable creation from elementsArray.from()
— universal for transformationsMethod choice depends on:
[]
is fastestArray.from()
are clearestnew Array()
everywhereRecommendations:
// For most cases
const arr = [1, 2, 3];
// For ranges and transformations
const range = Array.from({length: 10}, (_, i) => i + 1);
// For copying and combining
const copy = [...original];
const combined = [...arr1, ...arr2];
// For creating from iterable objects
const fromSet = [...new Set([1, 2, 2, 3])];
Understanding the differences between methods is the foundation for efficient array work in JavaScript!
Want more interview preparation articles? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪