JavaScript Arrays
Learn how to create, access, modify, search, sort, transform, iterate, copy, combine, destructure, and work with arrays in JavaScript using built-in methods and real-world examples.
Introduction
Arrays are one of the most important data structures in JavaScript. They allow multiple values to be stored, organized, accessed, modified, searched, sorted, filtered, and transformed using a single variable.
Almost every real-world application uses arrays. Product lists, shopping carts, student records, messages, search results, API responses, notifications, tasks, scores, images, and navigation items are commonly represented as arrays.
JavaScript arrays are dynamic. Their size can grow or shrink while the program runs, and they can store values of different data types.
JavaScript also provides powerful array methods such as map(), filter(), reduce(), find(), some(), every(), sort(), slice(), splice(), and many others for processing collections of data.
- What arrays are in JavaScript.
- Why arrays are important.
- How to create arrays.
- How array indexes work.
- How to access and modify elements.
- How to find array length.
- How to add elements.
- How to remove elements.
- How push() and pop() work.
- How shift() and unshift() work.
- How slice() and splice() work.
- How to combine arrays.
- How to search arrays.
- How find() and findIndex() work.
- How some() and every() work.
- How to iterate through arrays.
- How forEach() works.
- How map() transforms arrays.
- How filter() selects elements.
- How reduce() combines values.
- How to sort arrays correctly.
- How to reverse arrays.
- How to copy arrays.
- How array destructuring works.
- How nested and multidimensional arrays work.
- How to flatten arrays.
- How array references behave.
- How to remove duplicate values.
- How to solve common array problems.
- How to build a complete product management example.
What is an Array?
An array is an ordered collection of values stored inside a single variable. Each value is called an element, and every element has a numeric position called an index.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(languages);Array indexes begin at 0. The first element is stored at index 0, the second at index 1, and so on.
Array: ['HTML', 'CSS', 'JavaScript']
│ │ │
Index: 0 1 2Why Do We Need Arrays?
Without arrays, storing a large collection of related values would require many separate variables. Arrays keep related data together and make it easier to process collections.
const student1 = 'Aarav';
const student2 = 'Priya';
const student3 = 'Rohan';
const student4 = 'Meera';const students = [
'Aarav',
'Priya',
'Rohan',
'Meera'
];
console.log(students);Shopping Carts
Store products selected by a customer.
User Lists
Manage collections of users, employees, students, or customers.
API Responses
Process collections of data received from backend services.
Task Managers
Store pending, completed, and filtered tasks.
Games
Manage players, enemies, scores, inventory, and game objects.
Product Catalogs
Store and process products, prices, categories, and stock.
Messages
Maintain chat history and notification collections.
Data Analysis
Calculate totals, averages, minimums, maximums, and grouped results.
Real-World Analogy
Think of an array like a row of numbered lockers. Each locker stores one value, and its locker number represents the array index.
ARRAY: ['HTML', 'CSS', 'JavaScript']
┌────────────┐
0 │ HTML │
├────────────┤
1 │ CSS │
├────────────┤
2 │ JavaScript │
└────────────┘
Each locker:
stores one element
has an index
can be accessed
can be replaced
The array:
keeps all related values togetherCreating Arrays
JavaScript provides several ways to create arrays. The array literal syntax is the most common and recommended approach.
Array Literal
An array literal uses square brackets to create an array.
const fruits = [
'Apple',
'Banana',
'Mango'
];
console.log(fruits);- Array literals are concise.
- They are easy to read.
- They avoid constructor confusion.
- Use [] for most array creation.
Array Constructor
Arrays can also be created using the Array constructor.
const colors = new Array(
'Red',
'Green',
'Blue'
);
console.log(colors);Using a single numeric argument with the Array constructor creates an empty array with that length instead of an array containing the number.
const first = new Array(5);
const second = [5];
console.log(first.length);
console.log(second.length);- new Array(5) creates five empty slots.
- [5] creates an array containing the number 5.
- Prefer array literal syntax in normal code.
Array.of()
Array.of() creates an array from the values passed to it and avoids the single-number behavior of the Array constructor.
const numbers = Array.of(5);
console.log(numbers);
console.log(numbers.length);Array.from()
Array.from() creates an array from an iterable or array-like value.
const characters =
Array.from('CODE');
console.log(characters);const numbers =
Array.from(
[1, 2, 3],
number => number * 2
);
console.log(numbers);Empty Arrays
An empty array contains no elements and has a length of zero.
const items = [];
console.log(items);
console.log(items.length);
console.log(Boolean(items));- An empty string is falsy.
- An empty array is truthy.
- Use array.length === 0 to check whether an array is empty.
Mixed Data Types
JavaScript arrays can contain values of different data types.
const values = [
'JavaScript',
2026,
true,
null,
undefined,
{ level: 'Beginner' },
['HTML', 'CSS']
];
console.log(values);Although mixed arrays are allowed, collections are often easier to understand when their elements represent the same kind of data.
Array Length
The length property returns the number of positions in an array.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(languages.length);Array Length: 3
Indexes:
0 → HTML
1 → CSS
2 → JavaScript
Final Index:
length - 1
3 - 1
2Accessing Array Elements
Array elements are accessed using square brackets and an index.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(languages[0]);
console.log(languages[1]);
console.log(languages[2]);Array Indexes
JavaScript array indexes begin at 0. Accessing a position that does not exist returns undefined.
const fruits = [
'Apple',
'Banana'
];
console.log(fruits[10]);Accessing the First Element
const colors = [
'Red',
'Green',
'Blue'
];
console.log(colors[0]);Accessing the Last Element
const colors = [
'Red',
'Green',
'Blue'
];
const lastColor =
colors[colors.length - 1];
console.log(lastColor);at() Method
The at() method supports positive and negative indexes.
const colors = [
'Red',
'Green',
'Blue'
];
console.log(colors.at(0));
console.log(colors.at(-1));
console.log(colors.at(-2));Modifying Array Elements
Unlike strings, arrays are mutable. Existing elements can be replaced directly using their indexes.
const languages = [
'HTML',
'CSS',
'Java'
];
languages[2] = 'JavaScript';
console.log(languages);- Existing elements can be replaced.
- Elements can be added.
- Elements can be removed.
- Many array methods modify the original array.
Adding Elements
Elements can be added to the beginning or end of an array.
push()
The push() method adds one or more elements to the end of an array and returns the new length.
const languages = [
'HTML',
'CSS'
];
const newLength =
languages.push('JavaScript');
console.log(languages);
console.log(newLength);unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length.
const languages = [
'CSS',
'JavaScript'
];
languages.unshift('HTML');
console.log(languages);Removing Elements
Elements can be removed from the beginning or end of an array using built-in methods.
pop()
The pop() method removes and returns the final element.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
const removed =
languages.pop();
console.log(removed);
console.log(languages);shift()
The shift() method removes and returns the first element.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
const removed =
languages.shift();
console.log(removed);
console.log(languages);Deleting Elements
The delete operator can remove an array property, but it leaves an empty slot and does not reduce the array length.
const fruits = [
'Apple',
'Banana',
'Mango'
];
delete fruits[1];
console.log(fruits);
console.log(fruits.length);- delete leaves an empty slot.
- The array length does not change.
- Use splice() when an element should be removed by index.
- Use filter() when elements should be removed by condition.
splice()
The splice() method can remove, replace, or insert elements directly inside an array.
const languages = [
'HTML',
'CSS',
'Java',
'JavaScript'
];
const removed =
languages.splice(2, 1);
console.log(removed);
console.log(languages);const languages = [
'HTML',
'JavaScript'
];
languages.splice(
1,
0,
'CSS'
);
console.log(languages);const languages = [
'HTML',
'Java',
'JavaScript'
];
languages.splice(
1,
1,
'CSS'
);
console.log(languages);Extracting Elements
A section of an array can be extracted without changing the original array.
slice()
The slice() method returns a shallow copy of part of an array.
const languages = [
'HTML',
'CSS',
'JavaScript',
'React'
];
const webBasics =
languages.slice(0, 3);
console.log(webBasics);
console.log(languages);Feature slice() splice()
--------------------------------------------------
Changes Original No Yes
Extract Elements Yes Yes
Remove Elements No Yes
Insert Elements No Yes
Replace Elements No YesCombining Arrays
Multiple arrays can be combined using concat() or spread syntax.
concat()
const frontend = [
'HTML',
'CSS'
];
const programming = [
'JavaScript',
'TypeScript'
];
const technologies =
frontend.concat(programming);
console.log(technologies);Spread Operator
Spread syntax expands array elements and is commonly used to combine or copy arrays.
const frontend = [
'HTML',
'CSS'
];
const programming = [
'JavaScript',
'TypeScript'
];
const technologies = [
...frontend,
...programming
];
console.log(technologies);Converting Arrays to Strings
Arrays can be converted into strings using toString() or join().
toString()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.toString()
);join()
The join() method combines array elements using a custom separator.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.join(' | ')
);Searching Arrays
JavaScript provides several methods for finding values and matching elements.
indexOf()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.indexOf('CSS')
);
console.log(
languages.indexOf('Python')
);lastIndexOf()
const numbers = [
10,
20,
10,
30,
10
];
console.log(
numbers.lastIndexOf(10)
);includes()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.includes('CSS')
);
console.log(
languages.includes('Python')
);find()
The find() method returns the first element that satisfies a condition.
const products = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Phone' },
{ id: 3, name: 'Tablet' }
];
const product =
products.find(
item => item.id === 2
);
console.log(product);findIndex()
The findIndex() method returns the index of the first matching element.
const products = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Phone' },
{ id: 3, name: 'Tablet' }
];
const index =
products.findIndex(
item => item.id === 2
);
console.log(index);findLast()
The findLast() method searches from the end and returns the first matching element encountered.
const numbers = [
10,
25,
30,
45
];
const result =
numbers.findLast(
number => number > 20
);
console.log(result);findLastIndex()
const numbers = [
10,
25,
30,
45
];
const index =
numbers.findLastIndex(
number => number > 20
);
console.log(index);Testing Array Elements
The some() and every() methods test whether array elements satisfy a condition.
some()
The some() method returns true if at least one element satisfies the condition.
const ages = [
15,
17,
22,
14
];
const hasAdult =
ages.some(
age => age >= 18
);
console.log(hasAdult);every()
The every() method returns true only when all elements satisfy the condition.
const scores = [
75,
80,
90,
65
];
const allPassed =
scores.every(
score => score >= 40
);
console.log(allPassed);Iterating Arrays
Iteration means processing array elements one by one.
for Loop
const languages = [
'HTML',
'CSS',
'JavaScript'
];
for (
let index = 0;
index < languages.length;
index++
) {
console.log(
index,
languages[index]
);
}for...of Loop
const languages = [
'HTML',
'CSS',
'JavaScript'
];
for (const language of languages) {
console.log(language);
}forEach()
The forEach() method executes a function once for every array element.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
languages.forEach(
function (language, index) {
console.log(
index,
language
);
}
);- Processes every element.
- Does not create a new array.
- Returns undefined.
- Cannot normally be stopped with break.
- Use it for side effects such as logging or DOM updates.
Transforming Arrays
Transformation creates a new array where each element is based on an original element.
map()
The map() method creates a new array by transforming every element.
const prices = [
100,
200,
300
];
const doubledPrices =
prices.map(
price => price * 2
);
console.log(prices);
console.log(doubledPrices);const users = [
{ name: 'Aarav', age: 25 },
{ name: 'Priya', age: 22 }
];
const names =
users.map(
user => user.name
);
console.log(names);Filtering Arrays
Filtering creates a new array containing only elements that satisfy a condition.
filter()
const numbers = [
10,
25,
30,
45,
50
];
const largeNumbers =
numbers.filter(
number => number >= 30
);
console.log(largeNumbers);const products = [
{
name: 'Laptop',
inStock: true
},
{
name: 'Phone',
inStock: false
},
{
name: 'Tablet',
inStock: true
}
];
const availableProducts =
products.filter(
product => product.inStock
);
console.log(availableProducts);Reducing Arrays
Reduction processes all elements and combines them into a single result.
reduce()
const prices = [
100,
200,
300
];
const total =
prices.reduce(
function (
accumulator,
price
) {
return accumulator + price;
},
0
);
console.log(total);Array: [100, 200, 300]
Initial Accumulator = 0
Step 1:
0 + 100 = 100
Step 2:
100 + 200 = 300
Step 3:
300 + 300 = 600
Final Result:
600const cart = [
{
name: 'Laptop',
price: 50000,
quantity: 1
},
{
name: 'Mouse',
price: 1000,
quantity: 2
}
];
const total =
cart.reduce(
(sum, item) =>
sum +
item.price *
item.quantity,
0
);
console.log(total);reduceRight()
The reduceRight() method works like reduce() but processes elements from right to left.
const letters = [
'A',
'B',
'C'
];
const result =
letters.reduceRight(
(text, letter) =>
text + letter,
''
);
console.log(result);Sorting Arrays
Sorting arranges elements into a particular order.
sort()
By default, sort() converts values to strings and compares them lexicographically.
const fruits = [
'Mango',
'Apple',
'Banana'
];
fruits.sort();
console.log(fruits);- sort() mutates the array.
- Default sorting is string-based.
- Numeric sorting requires a compare function.
- Use toSorted() when the original array should remain unchanged.
Numeric Sorting
const numbers = [
100,
5,
20,
3
];
numbers.sort();
console.log(numbers);const numbers = [
100,
5,
20,
3
];
numbers.sort(
(a, b) => a - b
);
console.log(numbers);const numbers = [
100,
5,
20,
3
];
numbers.sort(
(a, b) => b - a
);
console.log(numbers);Sorting Objects
const products = [
{
name: 'Laptop',
price: 50000
},
{
name: 'Mouse',
price: 1000
},
{
name: 'Phone',
price: 30000
}
];
products.sort(
(a, b) =>
a.price - b.price
);
console.log(products);toSorted()
The toSorted() method returns a sorted copy without changing the original array.
const numbers = [
30,
10,
20
];
const sorted =
numbers.toSorted(
(a, b) => a - b
);
console.log(numbers);
console.log(sorted);Reversing Arrays
Reversing changes the order of elements from end to beginning.
reverse()
const numbers = [
1,
2,
3,
4
];
numbers.reverse();
console.log(numbers);toReversed()
The toReversed() method returns a reversed copy without modifying the original array.
const numbers = [
1,
2,
3
];
const reversed =
numbers.toReversed();
console.log(numbers);
console.log(reversed);Copying Arrays
Assigning an array to another variable does not create an independent copy. Both variables reference the same array.
const original = [
'HTML',
'CSS'
];
const copy = original;
copy.push('JavaScript');
console.log(original);
console.log(copy);const original = [
'HTML',
'CSS'
];
const copy = [...original];
copy.push('JavaScript');
console.log(original);
console.log(copy);Shallow Copies
Spread syntax, slice(), and Array.from() create shallow copies. Nested objects and arrays are still shared by reference.
const original = [
{
name: 'Aarav'
}
];
const copy = [...original];
copy[0].name = 'Priya';
console.log(original[0].name);
console.log(copy[0].name);Array Destructuring
Array destructuring extracts values from an array into variables.
const languages = [
'HTML',
'CSS',
'JavaScript'
];
const [
first,
second,
third
] = languages;
console.log(first);
console.log(second);
console.log(third);Skipping Elements
const values = [
'A',
'B',
'C'
];
const [
first,
,
third
] = values;
console.log(first);
console.log(third);Default Values
const colors = ['Red'];
const [
primary,
secondary = 'Blue'
] = colors;
console.log(primary);
console.log(secondary);Rest Pattern
The rest pattern collects remaining elements into a new array.
const numbers = [
10,
20,
30,
40
];
const [
first,
...remaining
] = numbers;
console.log(first);
console.log(remaining);Swapping Variables
let first = 'A';
let second = 'B';
[
first,
second
] = [
second,
first
];
console.log(first);
console.log(second);Nested Arrays
An array can contain other arrays as elements.
const courses = [
[
'HTML',
'CSS'
],
[
'JavaScript',
'TypeScript'
]
];
console.log(courses);Multidimensional Arrays
A multidimensional array represents data using multiple levels of arrays, such as rows and columns.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix); Column
0 1 2
Row 0 1 2 3
Row 1 4 5 6
Row 2 7 8 9Accessing Nested Values
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][0]);
console.log(matrix[1][2]);
console.log(matrix[2][1]);Flattening Arrays
Flattening converts nested arrays into a simpler array structure.
flat()
const nested = [
1,
[2, 3],
[4, 5]
];
const result =
nested.flat();
console.log(result);const nested = [
1,
[2, [3, [4]]]
];
const result =
nested.flat(Infinity);
console.log(result);flatMap()
The flatMap() method maps every element and then flattens the result by one level.
const sentences = [
'Learn JavaScript',
'Build Projects'
];
const words =
sentences.flatMap(
sentence =>
sentence.split(' ')
);
console.log(words);Checking Arrays
Because arrays are objects, typeof cannot reliably distinguish arrays from other objects.
const values = [];
console.log(typeof values);Array.isArray()
console.log(
Array.isArray([])
);
console.log(
Array.isArray({})
);
console.log(
Array.isArray('JavaScript')
);Array References
Arrays are reference values. Variables store references to arrays rather than independent copies of their contents.
const first = [
'HTML',
'CSS'
];
const second = first;
second.push('JavaScript');
console.log(first);Comparing Arrays
Two different arrays are not equal even when they contain identical values because they have different references.
const first = [1, 2, 3];
const second = [1, 2, 3];
const third = first;
console.log(first === second);
console.log(first === third);Clearing Arrays
const items = [
'A',
'B',
'C'
];
items.length = 0;
console.log(items);let items = [
'A',
'B',
'C'
];
items = [];
console.log(items);Removing Duplicates
A Set stores unique values. Combining Set with spread syntax is a common way to remove primitive duplicates.
const numbers = [
1,
2,
2,
3,
3,
4
];
const uniqueNumbers = [
...new Set(numbers)
];
console.log(uniqueNumbers);Grouping Data
Arrays can be grouped into categories using reduce().
const products = [
{
name: 'Laptop',
category: 'Electronics'
},
{
name: 'Phone',
category: 'Electronics'
},
{
name: 'Chair',
category: 'Furniture'
}
];
const grouped =
products.reduce(
function (
result,
product
) {
const category =
product.category;
if (!result[category]) {
result[category] = [];
}
result[category].push(
product
);
return result;
},
{}
);
console.log(grouped);Common Array Patterns
Certain array-processing patterns appear repeatedly in real applications and programming problems.
Sum of Numbers
function calculateSum(numbers) {
return numbers.reduce(
(sum, number) =>
sum + number,
0
);
}
console.log(
calculateSum(
[10, 20, 30, 40]
)
);Maximum and Minimum
const numbers = [
10,
50,
20,
80,
30
];
const maximum =
Math.max(...numbers);
const minimum =
Math.min(...numbers);
console.log(maximum);
console.log(minimum);Count Occurrences
const fruits = [
'Apple',
'Banana',
'Apple',
'Mango',
'Apple'
];
const counts =
fruits.reduce(
function (
result,
fruit
) {
result[fruit] =
(result[fruit] || 0) + 1;
return result;
},
{}
);
console.log(counts);Unique Values
function getUniqueValues(values) {
return [...new Set(values)];
}
console.log(
getUniqueValues(
[1, 1, 2, 3, 3, 4]
)
);Chunk an Array
Chunking divides a large array into smaller arrays of a specified size.
function chunkArray(
array,
size
) {
const chunks = [];
for (
let index = 0;
index < array.length;
index += size
) {
chunks.push(
array.slice(
index,
index + size
)
);
}
return chunks;
}
console.log(
chunkArray(
[1, 2, 3, 4, 5, 6, 7],
3
)
);Shuffle an Array
The Fisher-Yates algorithm can shuffle an array by swapping elements from the end toward the beginning.
function shuffleArray(array) {
const shuffled = [...array];
for (
let index =
shuffled.length - 1;
index > 0;
index--
) {
const randomIndex =
Math.floor(
Math.random() *
(index + 1)
);
[
shuffled[index],
shuffled[randomIndex]
] = [
shuffled[randomIndex],
shuffled[index]
];
}
return shuffled;
}
console.log(
shuffleArray(
[1, 2, 3, 4, 5]
)
);Complete Array Example
The following example builds a product manager that uses arrays for storing, searching, filtering, sorting, adding, and removing products.
<div class="product-manager">
<h2>Product Manager</h2>
<div class="product-form">
<input
id="productName"
type="text"
placeholder="Product name"
>
<input
id="productPrice"
type="number"
placeholder="Price"
>
<button id="addProductButton">
Add Product
</button>
</div>
<div class="product-controls">
<input
id="searchInput"
type="text"
placeholder="Search products..."
>
<select id="sortSelect">
<option value="default">
Default Order
</option>
<option value="price-low">
Price: Low to High
</option>
<option value="price-high">
Price: High to Low
</option>
<option value="name">
Name
</option>
</select>
</div>
<div id="productList"></div>
<div class="summary">
<p>
Products:
<strong id="productCount">
0
</strong>
</p>
<p>
Total Value:
₹<strong id="totalValue">
0
</strong>
</p>
</div>
</div>let products = [
{
id: 1,
name: 'Laptop',
price: 50000
},
{
id: 2,
name: 'Phone',
price: 30000
},
{
id: 3,
name: 'Mouse',
price: 1000
}
];
const productName =
document.getElementById(
'productName'
);
const productPrice =
document.getElementById(
'productPrice'
);
const addProductButton =
document.getElementById(
'addProductButton'
);
const searchInput =
document.getElementById(
'searchInput'
);
const sortSelect =
document.getElementById(
'sortSelect'
);
const productList =
document.getElementById(
'productList'
);
const productCount =
document.getElementById(
'productCount'
);
const totalValue =
document.getElementById(
'totalValue'
);
addProductButton.addEventListener(
'click',
addProduct
);
searchInput.addEventListener(
'input',
renderProducts
);
sortSelect.addEventListener(
'change',
renderProducts
);
function addProduct() {
const name =
productName.value.trim();
const price =
Number(productPrice.value);
if (
name === '' ||
price <= 0
) {
alert(
'Enter a valid product name and price.'
);
return;
}
const product = {
id: Date.now(),
name,
price
};
products.push(product);
productName.value = '';
productPrice.value = '';
renderProducts();
}
function removeProduct(id) {
products =
products.filter(
product =>
product.id !== id
);
renderProducts();
}
function getVisibleProducts() {
const searchText =
searchInput.value
.trim()
.toLowerCase();
let visibleProducts =
products.filter(
product =>
product.name
.toLowerCase()
.includes(searchText)
);
const sortValue =
sortSelect.value;
if (
sortValue === 'price-low'
) {
visibleProducts =
visibleProducts.toSorted(
(a, b) =>
a.price - b.price
);
}
if (
sortValue === 'price-high'
) {
visibleProducts =
visibleProducts.toSorted(
(a, b) =>
b.price - a.price
);
}
if (
sortValue === 'name'
) {
visibleProducts =
visibleProducts.toSorted(
(a, b) =>
a.name.localeCompare(
b.name
)
);
}
return visibleProducts;
}
function renderProducts() {
const visibleProducts =
getVisibleProducts();
productList.innerHTML = '';
visibleProducts.forEach(
function (product) {
const card =
document.createElement(
'div'
);
card.className =
'product-card';
const title =
document.createElement(
'h3'
);
title.textContent =
product.name;
const price =
document.createElement(
'p'
);
price.textContent =
`₹${product.price}`;
const removeButton =
document.createElement(
'button'
);
removeButton.textContent =
'Remove';
removeButton.addEventListener(
'click',
function () {
removeProduct(
product.id
);
}
);
card.append(
title,
price,
removeButton
);
productList.appendChild(
card
);
}
);
updateSummary();
}
function updateSummary() {
productCount.textContent =
products.length;
const total =
products.reduce(
(sum, product) =>
sum + product.price,
0
);
totalValue.textContent =
total;
}
renderProducts();- Storing objects inside an array.
- Adding elements with push().
- Removing elements with filter().
- Searching array data.
- Using includes() for text matching.
- Sorting arrays by numbers.
- Sorting arrays by strings.
- Using toSorted() without mutating source data.
- Iterating with forEach().
- Calculating totals with reduce().
- Using array length.
- Rendering array data into the DOM.
- Keeping interface data synchronized with an array.
Array Processing Flow
RAW COLLECTION
│
▼
┌──────────────────────────┐
│ RECEIVE ARRAY │
│ │
│ API Response │
│ User Input │
│ Database Records │
│ Application State │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ SEARCH / TEST │
│ │
│ find() │
│ includes() │
│ some() │
│ every() │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ FILTER │
│ │
│ filter() │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ TRANSFORM │
│ │
│ map() │
│ flatMap() │
│ sort() │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ COMBINE │
│ │
│ reduce() │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ OUTPUT │
│ │
│ Display │
│ Store │
│ Send to API │
│ Update State │
└──────────────────────────┘Real-World Applications
Shopping Carts
Store products, quantities, prices, and calculate totals.
Product Catalogs
Search, filter, sort, and display product collections.
User Management
Manage users, roles, permissions, and account collections.
Task Applications
Store, filter, update, and remove tasks.
Chat Systems
Maintain ordered collections of messages and conversations.
Analytics
Calculate totals, averages, counts, maximums, and grouped results.
Games
Manage inventories, players, enemies, scores, and levels.
API Data
Process lists of records received from backend services.
Search Results
Filter and sort matching records based on user queries.
Playlists
Store, reorder, search, and remove songs or videos.
Common Beginner Mistakes
- Forgetting that array indexes begin at 0.
- Using length as the final valid index.
- Forgetting that the final normal index is length - 1.
- Accessing indexes that do not exist.
- Assuming an empty array is falsy.
- Using typeof to check whether a value is an array.
- Using new Array(number) when an array containing that number is intended.
- Using delete to remove array elements.
- Confusing push() with unshift().
- Confusing pop() with shift().
- Forgetting that push() returns the new length.
- Expecting pop() to return the new array.
- Confusing slice() with splice().
- Forgetting that splice() modifies the original array.
- Forgetting that slice() does not modify the original array.
- Using the wrong delete count with splice().
- Forgetting that the end index in slice() is excluded.
- Assuming concat() modifies the original array.
- Assigning an array to another variable and expecting an independent copy.
- Forgetting that spread syntax creates only a shallow copy.
- Comparing separate arrays with === and expecting content comparison.
- Forgetting that arrays are reference values.
- Mutating shared array references accidentally.
- Using indexOf() for object property searches.
- Using includes() to search objects by property.
- Forgetting that find() returns one element.
- Confusing find() with filter().
- Forgetting that findIndex() returns -1 when no match exists.
- Confusing some() with every().
- Using forEach() when a new array is required.
- Expecting forEach() to return transformed values.
- Using map() only for side effects.
- Forgetting to return a value from a map() callback.
- Confusing map() with filter().
- Returning transformed values from filter() instead of booleans.
- Using reduce() without understanding the accumulator.
- Omitting an initial reduce() value when the data may be empty.
- Using default sort() for numbers.
- Forgetting that sort() mutates the original array.
- Forgetting that reverse() mutates the original array.
- Using sort(() => Math.random() - 0.5) for reliable shuffling.
- Forgetting that nested arrays require multiple indexes.
- Using flat() without choosing the required depth.
- Assuming Array.isArray() and typeof provide the same result.
- Removing duplicates from objects using Set without understanding reference equality.
- Clearing one reference by reassignment while expecting other references to change.
- Modifying an array while iterating over it without considering index changes.
- Creating sparse arrays accidentally.
- Using array methods without checking whether the browser environment supports newer methods.
- Using mutating methods when immutable updates are required.
- Writing long method chains that are difficult to understand.
- Ignoring empty arrays in calculations.
- Assuming Math.max(array) works without spread syntax.
- Forgetting that filter() always returns an array.
- Forgetting that find() may return undefined.
- Using array indexes as permanent identifiers for changing data.
- Rendering untrusted array content with innerHTML.
// ❌ Wrong final index
const values = ['A', 'B', 'C'];
console.log(
values[values.length]
);
// undefined
// ❌ Empty arrays are truthy
if ([]) {
console.log('Runs');
}
// ❌ typeof cannot identify arrays
console.log(typeof []);
// object
// ❌ delete leaves an empty slot
const fruits = [
'Apple',
'Banana'
];
delete fruits[0];
console.log(fruits);
// ❌ Default numeric sorting
console.log(
[100, 5, 20].sort()
);
// [100, 20, 5]
// ❌ Reference copy
const first = [1, 2];
const second = first;
second.push(3);
console.log(first);
// [1, 2, 3]
// ❌ Separate arrays are not equal
console.log(
[1, 2] === [1, 2]
);
// falseBest Practices
- Use array literal syntax for most arrays.
- Use meaningful plural names such as users, products, or messages.
- Remember that indexes begin at zero.
- Use array.length - 1 for the final normal index.
- Use at(-1) for readable access to the final element.
- Use Array.isArray() to check arrays.
- Use push() and pop() for end operations.
- Use shift() and unshift() only when beginning operations are required.
- Avoid delete for removing array elements.
- Use splice() for direct index-based mutation.
- Use slice() for non-mutating extraction.
- Understand which methods mutate the original array.
- Prefer non-mutating methods when predictable state updates are important.
- Use toSorted() when sorting should preserve the original array.
- Use toReversed() when reversing should preserve the original array.
- Use spread syntax for simple shallow copies.
- Remember that spread syntax does not deep-clone nested data.
- Use find() when one matching element is required.
- Use filter() when multiple matching elements are required.
- Use includes() for primitive existence checks.
- Use some() to test whether at least one element matches.
- Use every() to test whether all elements match.
- Use for...of for straightforward value iteration.
- Use forEach() for side effects.
- Use map() for transformations.
- Use filter() for selection.
- Use reduce() for totals and aggregation.
- Provide a clear initial value to reduce().
- Use numeric compare functions when sorting numbers.
- Use localeCompare() when sorting human-language strings.
- Do not use array indexes as stable identifiers for dynamic records.
- Use unique IDs for products, users, tasks, and similar records.
- Handle empty arrays before calculations when necessary.
- Check find() results before accessing properties.
- Use destructuring when it improves readability.
- Use the rest pattern for remaining elements.
- Use flat() only to the depth actually required.
- Use flatMap() when mapping naturally produces nested arrays.
- Use Set for removing duplicate primitive values.
- Use Fisher-Yates for reliable array shuffling.
- Avoid mutating an array unexpectedly through shared references.
- Keep complex array transformations in named functions.
- Break long method chains into readable intermediate steps.
- Choose method names based on intent rather than convenience.
- Do not use map() when forEach() better expresses the intent.
- Do not use filter() when find() is sufficient.
- Avoid unnecessary repeated sorting or filtering.
- Use const when the array variable itself is not reassigned.
- Remember that const arrays can still be mutated.
- Validate external data before assuming it is an array.
- Treat API collections as potentially empty.
- Avoid sparse arrays unless there is a specific reason.
- Use textContent when rendering plain array values into the DOM.
- Test array utilities with empty arrays.
- Test array utilities with one element.
- Test array utilities with duplicate values.
- Test array utilities with nested values when relevant.
- Keep array-processing code readable and predictable.
Frequently Asked Questions
What is an array in JavaScript?
An array is an ordered collection of values stored inside a single variable.
What is an array element?
An element is an individual value stored inside an array.
What is an array index?
An index is the numeric position of an element.
What index does an array begin with?
JavaScript arrays begin at index 0.
How do I create an array?
The most common approach is array literal syntax using square brackets.
What is the difference between [] and new Array()?
Both can create arrays, but array literals are simpler and avoid special behavior with a single numeric constructor argument.
What does Array.of() do?
It creates an array containing the values passed to it.
What does Array.from() do?
It creates an array from an iterable or array-like value.
Is an empty array truthy or falsy?
An empty array is truthy.
How do I check whether an array is empty?
Check whether array.length === 0.
Can arrays contain different data types?
Yes. JavaScript arrays can contain values of different types.
How do I find the number of elements?
Use the length property.
What is the last normal array index?
The final normal index is array.length - 1.
How do I access the first element?
Use array[0].
How do I access the last element?
Use array.at(-1) or array[array.length - 1].
What happens when I access an invalid index?
JavaScript returns undefined.
Are arrays mutable?
Yes. Array elements can be added, removed, and replaced.
Can a const array be modified?
Yes. const prevents reassignment of the variable but does not make the array immutable.
How do I add an element to the end?
Use push().
How do I add an element to the beginning?
Use unshift().
How do I remove the last element?
Use pop().
How do I remove the first element?
Use shift().
Should I use delete on arrays?
Usually no. It leaves an empty slot without reducing the array length.
What does splice() do?
It can insert, remove, or replace elements and modifies the original array.
What does slice() do?
It returns a shallow copy of part of an array without modifying the original.
What is the difference between slice() and splice()?
slice() extracts without mutation, while splice() changes the original array.
How do I combine arrays?
Use concat() or spread syntax.
How do I convert an array to a string?
Use toString() or join().
What is the difference between toString() and join()?
join() allows you to choose the separator.
How do I find the index of a value?
Use indexOf() for primitive values or findIndex() for condition-based searching.
What does indexOf() return when no match exists?
It returns -1.
How do I check whether an array contains a primitive value?
Use includes().
What does find() return?
It returns the first matching element or undefined.
What does filter() return?
It returns a new array containing all matching elements.
What is the difference between find() and filter()?
find() returns one matching element, while filter() returns an array of all matches.
What does some() do?
It returns true when at least one element satisfies a condition.
What does every() do?
It returns true only when every element satisfies a condition.
How do I loop through an array?
Use a for loop, for...of loop, or array iteration method.
What does forEach() return?
It returns undefined.
What does map() do?
It creates a new array by transforming every element.
What does filter() do?
It creates a new array containing elements that pass a condition.
What does reduce() do?
It combines array elements into a single result such as a total, object, or other accumulated value.
Should reduce() have an initial value?
Providing an initial value is usually clearer and safer, especially for potentially empty arrays.
Why does sort() sort numbers incorrectly?
Default sorting compares values as strings.
How do I sort numbers in ascending order?
Use array.sort((a, b) => a - b).
How do I sort numbers in descending order?
Use array.sort((a, b) => b - a).
Does sort() modify the original array?
Yes.
What does toSorted() do?
It returns a sorted copy without changing the original array.
Does reverse() modify the original array?
Yes.
What does toReversed() do?
It returns a reversed copy without changing the original array.
How do I copy an array?
Use spread syntax, slice(), or Array.from() for a shallow copy.
What is a shallow copy?
It creates a new outer array while nested objects and arrays remain shared references.
What is array destructuring?
It extracts array elements into variables using a concise syntax.
How do I collect remaining destructured values?
Use the rest pattern.
Can destructuring swap variables?
Yes. Array destructuring provides a concise way to swap values.
What is a nested array?
It is an array containing another array.
What is a multidimensional array?
It is an array structure with multiple levels, often used for rows and columns.
What does flat() do?
It creates a new array with nested arrays flattened to a specified depth.
What does flatMap() do?
It maps each element and then flattens the result by one level.
Why does typeof [] return object?
Arrays are specialized objects in JavaScript.
How do I correctly check for an array?
Use Array.isArray().
Why are two identical arrays not equal with ===?
Separate arrays have different references.
How do I remove duplicate primitive values?
A common approach is [...new Set(array)].
How do I calculate an array total?
Use reduce() or a loop.
How do I find the maximum array number?
Use Math.max(...array).
How do I find the minimum array number?
Use Math.min(...array).
How do I divide an array into chunks?
Loop through the array in steps and use slice() for each chunk.
How should I shuffle an array?
Use a proper algorithm such as Fisher-Yates.
Key Takeaways
- Arrays store ordered collections of values.
- Array indexes begin at zero.
- The final normal index is length - 1.
- Array literals are the preferred creation syntax.
- Arrays can contain different data types.
- Empty arrays are truthy.
- Arrays are mutable.
- push() adds to the end.
- pop() removes from the end.
- unshift() adds to the beginning.
- shift() removes from the beginning.
- Avoid delete for array element removal.
- splice() changes array contents.
- slice() extracts without modifying the original.
- concat() combines arrays.
- Spread syntax can combine and copy arrays.
- join() converts array elements into formatted text.
- indexOf() finds primitive positions.
- includes() checks primitive existence.
- find() returns the first matching element.
- findIndex() returns the first matching index.
- some() tests whether at least one element matches.
- every() tests whether all elements match.
- forEach() performs side effects for every element.
- map() transforms every element.
- filter() selects matching elements.
- reduce() combines elements into one result.
- Default sort() is string-based.
- Numeric sorting requires a compare function.
- sort() and reverse() mutate arrays.
- toSorted() and toReversed() preserve the original.
- Arrays are reference values.
- Spread syntax creates shallow copies.
- Separate arrays are not equal by content using ===.
- Destructuring extracts array values.
- Nested arrays contain other arrays.
- flat() removes nesting levels.
- Array.isArray() correctly identifies arrays.
- Set can remove duplicate primitive values.
- Arrays are essential for real-world application data.
Summary
Arrays are ordered collections that allow multiple values to be stored and processed using a single variable.
JavaScript arrays use zero-based indexes and provide direct access to elements. Unlike strings, arrays are mutable, so their contents can be added, removed, replaced, sorted, and reorganized.
Methods such as push(), pop(), shift(), unshift(), slice(), and splice() provide control over array structure.
Searching methods such as includes(), find(), and findIndex() help locate data, while some() and every() test array conditions.
Iteration and transformation methods such as forEach(), map(), filter(), and reduce() are fundamental tools for modern JavaScript development.
Arrays are reference values, so copying and comparison require special attention. Spread syntax creates shallow copies, while separate arrays are not equal simply because their contents look identical.
Nested arrays, destructuring, flattening, sorting, grouping, duplicate removal, and aggregation allow complex collections to be processed efficiently.
Mastering arrays is essential because most real-world applications work with collections of products, users, tasks, messages, records, search results, and API data.
- You understand what JavaScript arrays are.
- You can create arrays.
- You understand array indexes.
- You can access array elements.
- You can modify array elements.
- You can find array length.
- You can use push().
- You can use pop().
- You can use shift().
- You can use unshift().
- You understand why delete should usually be avoided.
- You can use splice().
- You can use slice().
- You can combine arrays.
- You can use spread syntax.
- You can convert arrays into strings.
- You can search arrays.
- You can use find() and findIndex().
- You can use some() and every().
- You can iterate through arrays.
- You can use forEach().
- You can transform arrays with map().
- You can select values with filter().
- You can aggregate data with reduce().
- You can sort arrays correctly.
- You can reverse arrays.
- You understand mutating and non-mutating methods.
- You can copy arrays.
- You understand shallow copies.
- You can use array destructuring.
- You can work with nested arrays.
- You can flatten arrays.
- You can identify arrays correctly.
- You understand array references.
- You can remove duplicate values.
- You can solve common array problems.
- You can build a complete product manager.
- You are ready to learn JavaScript Objects.