JavaScript Arrays: Complete Guide
Master working with arrays in JavaScript. From basic operations to advanced methods, this guide covers everything you need to know about arrays and how to use them effectively in your applications.
What are Arrays?
An array is an ordered collection of elements stored in a single variable. Arrays are one of the most fundamental data structures in JavaScript and are used to store multiple values of the same or different types. Each element in an array has an index (starting from 0) that identifies its position.
Creating Arrays in JavaScript
// Creating arrays
const fruits = ['apple', 'banana', 'orange'];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, 'hello', true, null];
// Accessing elements
console.log(fruits[0]); // 'apple'
console.log(fruits.length); // 3Learn how to create arrays and access elements using index positions. Arrays store multiple values in a single variable and are one of the most commonly used JavaScript data structures.
How to Create Arrays
There are multiple ways to create arrays in JavaScript. Each method is useful in different scenarios.
1. Array Literal (Recommended)
The most common and preferred way to create arrays. Use square brackets [] with comma-separated values.
Create Arrays Using Array Literals
// Empty array
const empty = [];
// Array with values
const fruits = ['apple', 'banana', 'orange'];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, 'hello', true, { name: 'John' }, null];
// Array with variables
const x = 10;
const arr = [x, x + 5, x * 2]; // [10, 15, 20]The array literal syntax [] is the most common way to create arrays in JavaScript. It is simple, readable, and widely used in modern applications.
2. Array Constructor
Use the new Array() constructor. Be careful with a single numeric argument - it creates an empty array with that length.
Create Arrays with the Array Constructor
// Creates array with specific length (contains empty slots)
const arr1 = new Array(5); // [empty × 5]
console.log(arr1.length); // 5
// Creates array with values
const arr2 = new Array(1, 2, 3); // [1, 2, 3]
const arr3 = new Array('a', 'b'); // ['a', 'b']
// CAUTION: Single number argument behaves differently
const arr4 = new Array(3); // [empty × 3]
const arr5 = new Array(3, 4); // [3, 4]JavaScript arrays can also be created using new Array(). It allows defining array values or creating arrays with a specific length.
3. Array.from()
Create an array from an iterable (string, Set, Map, NodeList) or array-like object.
Convert Data to Arrays with Array.from()
// From a string
const str = 'hello';
const chars = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
// From a Set
const set = new Set([1, 2, 3, 3, 2, 1]);
const arr = Array.from(set); // [1, 2, 3]
// With mapping function
const numbers = [1, 2, 3];
const doubled = Array.from(numbers, x => x * 2); // [2, 4, 6]
// From object with length property
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const arr2 = Array.from(arrayLike); // ['a', 'b', 'c']Array.from() creates a new array from iterable or array-like objects such as strings, sets, and node lists.
4. Array.of()
Create an array from its arguments. Solves the single-number argument issue of new Array().
Create Arrays Using Array.of()
// Unlike new Array(3), Array.of(3) creates [3]
const arr1 = Array.of(3); // [3]
const arr2 = Array.of(3, 4, 5); // [3, 4, 5]
// Always treats arguments as elements, not length
const arr3 = Array.of(1); // [1] (not [empty × 1])Array.of() creates a new array from the provided arguments and always treats them as elements.
5. Spread Operator (...)
Spread operator expands iterables into array elements. Great for copying or combining arrays.
Using the Spread Operator with Arrays
// Copy an array
const original = [1, 2, 3];
const copy = [...original]; // [1, 2, 3]
// Combine arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
// Add elements while combining
const merged = [0, ...arr1, 2.5, ...arr2, 5]; // [0, 1, 2, 2.5, 3, 4, 5]
// From string
const letters = [...'hello']; // ['h', 'e', 'l', 'l', 'o']The spread operator ... expands array elements. It is commonly used to copy, merge, or combine arrays.
6. Creating Arrays of Specific Size with Defaults
Create arrays with a specific length filled with default values.
Create Arrays with Default Values
// Fill with 0
const zeros = new Array(5).fill(0); // [0, 0, 0, 0, 0]
// Fill with string
const repeated = new Array(3).fill('x'); // ['x', 'x', 'x']
// Using Array.from for more control
const range = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
const evens = Array.from({ length: 5 }, (_, i) => i * 2); // [0, 2, 4, 6, 8]Use fill() or Array.from() to create arrays with a fixed size and predefined values.
7. Using Array Methods (Advanced)
Create arrays by transforming existing ones.
Generate Arrays Using Array Methods
// Using map() to create array
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2); // [2, 4, 6]
// Using filter() to create array
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0); // [2, 4, 6]
// Using split() to create array from string
const csv = 'apple,banana,orange';
const fruits = csv.split(','); // ['apple', 'banana', 'orange']Methods like map(), filter(), and split() help transform existing data into new arrays.
💡 Best Practice: Use array literal syntax [1, 2, 3] for most cases. Use Array.from() or spread operator when transforming other data structures.
Why Master Arrays?
- ✓Essential for Data Management: Arrays are crucial for organizing and manipulating collections of data
- ✓Coding Interviews: Array problems are common in technical interviews
- ✓Performance Optimization: Choosing the right array method impacts your code's efficiency
- ✓Working with APIs: Most data from APIs comes in array format (JSON arrays)
- ✓Frontend Development: React, Vue, and Angular heavily rely on array manipulation
Array Methods & Topics
Array Methods
Learn push, pop, shift, unshift and other basic operations
map()
Transform array elements with the map() method
filter()
Filter array elements based on conditions
reduce()
Combine array elements into a single value
find()
Find the first matching element
findIndex()
Find the index of the first matching element
some()
Check if any element matches a condition
every()
Check if all elements match a condition
sort()
Sort array elements
slice()
Extract a portion of an array
splice()
Add or remove elements from an array
flat()
Flatten nested arrays
forEach()
Iterate through array elements
Array Destructuring
Extract values from arrays into variables
Multidimensional Arrays
Work with nested arrays
Key Concepts
Array Index
Arrays use zero-based indexing, meaning the first element is at index 0.
Access Array Elements Using Index
const arr = ['a', 'b', 'c'];
console.log(arr[0]); // 'a'
console.log(arr[1]); // 'b'
console.log(arr[2]); // 'c'JavaScript arrays use zero-based indexing, meaning the first element starts at index 0. You can access elements using bracket notation like array[index].
Array Length
The length property returns the number of elements in an array.
Get and Modify Array Length
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // 3
// You can modify the length
fruits.length = 2; // Trims array to 2 elements
console.log(fruits); // ['apple', 'banana']The length property returns the number of elements in an array. It can also be used to truncate or expand an array.
Array Methods Categories
Mutating Methods: Modify the original array (push, pop, shift, unshift, splice, sort, reverse)
Non-Mutating Methods: Return a new array without modifying the original (map, filter, slice, concat)
Iterator Methods: Execute a function for each element (forEach, map, filter, reduce)
Search Methods: Find specific elements (find, findIndex, includes, indexOf)
Common Array Mistakes
❌ Forgetting Array is Zero-Indexed
Array Index Starts From Zero
const arr = [1, 2, 3];
console.log(arr[1]); // 2, not 1!JavaScript arrays start from index 0. Accessing arr[1] returns the second element, not the first.
Always remember: first element is at index 0, not 1
❌ Using == Instead of Deep Comparison
Array Comparison in JavaScript
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
console.log(arr1 == arr2); // false (different references)
console.log(JSON.stringify(arr1) === JSON.stringify(arr2)); // trueArrays are compared by reference, not by value. Two arrays with the same elements are still different unless they reference the same object.
Arrays are compared by reference, not by value
❌ Mutating Original Array Accidentally
Avoid Mutating the Original Array
const original = [1, 2, 3];
const sorted = original.sort(); // Mutates original!
console.log(original); // [1, 2, 3] - changed!
// Better:
const sorted = [...original].sort(); // Creates copy firstSome methods like sort() modify the original array. Use the spread operator or slice() to create a copy before sorting or modifying.
Some array methods mutate the original array. Use spread operator or slice() to create a copy
❌ Not Checking for Empty Arrays
Check for Empty Arrays Safely
const arr = [];
console.log(arr[0]); // undefined (not an error)
// Better:
if (arr.length > 0) {
console.log(arr[0]);
}Accessing an index in an empty array returns undefined. Always check array.length before accessing elements.
Always check array length before accessing elements
Frequently Asked Questions
How do I create an array?
You can create arrays using array literals [] or the Array constructor. Array literals are preferred: const arr = [1, 2, 3];
What's the difference between forEach and map?
forEach doesn't return anything and is used for side effects. map returns a new array with transformed elements and should be used when you need the results.
When should I use filter vs find?
Use find() to get the first matching element, and filter() to get all matching elements. find() returns a single value, filter() returns an array.
How do I remove duplicates from an array?
Remove Duplicate Values from an Array
const arr = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]You can remove duplicates using the Set object and the spread operator to create a new array with unique values.
What's the best way to copy an array?
Use the spread operator [...arr], slice() method, or Array.from(). Avoid direct assignment (newArr = oldArr) as it only copies the reference.
Ready to Dive Deeper?
Choose an array method above and learn how to use it with practical examples. Each topic includes real-world use cases and common pitfalls to avoid.
Start with Array Methods →