LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1755 min read

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 You Will Learn
  • 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.

Basic Array
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(languages);
Output

Click Run to see what this code prints.

Array indexes begin at 0. The first element is stored at index 0, the second at index 1, and so on.

Array Indexes
Array: ['HTML', 'CSS', 'JavaScript']
│ │ │
Index: 0 1 2

Why 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.

Without an Array
const student1 = 'Aarav';
const student2 = 'Priya';
const student3 = 'Rohan';
const student4 = 'Meera';
With an Array
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.

Locker Analogy
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 together

Creating 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.

Array Literal
const fruits = [
'Apple',
'Banana',
'Mango'
];
console.log(fruits);
Output

Click Run to see what this code prints.

Recommended Syntax
  • 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.

Array Constructor
const colors = new Array(
'Red',
'Green',
'Blue'
);
console.log(colors);
Output

Click Run to see what this code prints.

Using a single numeric argument with the Array constructor creates an empty array with that length instead of an array containing the number.

Constructor Confusion
const first = new Array(5);
const second = [5];
console.log(first.length);
console.log(second.length);
Output

Click Run to see what this code prints.

Constructor Warning
  • 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.

Array.of()
const numbers = Array.of(5);
console.log(numbers);
console.log(numbers.length);
Output

Click Run to see what this code prints.

Array.from()

Array.from() creates an array from an iterable or array-like value.

String to Array
const characters =
Array.from('CODE');
console.log(characters);
Output

Click Run to see what this code prints.

Array.from() with Mapping
const numbers =
Array.from(
[1, 2, 3],
number => number * 2
);
console.log(numbers);
Output

Click Run to see what this code prints.

Empty Arrays

An empty array contains no elements and has a length of zero.

Empty Array
const items = [];
console.log(items);
console.log(items.length);
console.log(Boolean(items));
Output

Click Run to see what this code prints.

Important Difference
  • 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.

Mixed Array
const values = [
'JavaScript',
2026,
true,
null,
undefined,
{ level: 'Beginner' },
['HTML', 'CSS']
];
console.log(values);
Output

Click Run to see what this code prints.

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.

Array Length
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(languages.length);
Output

Click Run to see what this code prints.

Length and Index
Array Length: 3
Indexes:
0 → HTML
1 → CSS
2 → JavaScript
Final Index:
length - 1
3 - 1
2

Accessing Array Elements

Array elements are accessed using square brackets and an index.

Accessing Elements
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(languages[0]);
console.log(languages[1]);
console.log(languages[2]);
Output

Click Run to see what this code prints.

Array Indexes

JavaScript array indexes begin at 0. Accessing a position that does not exist returns undefined.

Invalid Index
const fruits = [
'Apple',
'Banana'
];
console.log(fruits[10]);
Output

Click Run to see what this code prints.

Accessing the First Element

First Element
const colors = [
'Red',
'Green',
'Blue'
];
console.log(colors[0]);
Output

Click Run to see what this code prints.

Accessing the Last Element

Last Element
const colors = [
'Red',
'Green',
'Blue'
];
const lastColor =
colors[colors.length - 1];
console.log(lastColor);
Output

Click Run to see what this code prints.

at() Method

The at() method supports positive and negative indexes.

Array at()
const colors = [
'Red',
'Green',
'Blue'
];
console.log(colors.at(0));
console.log(colors.at(-1));
console.log(colors.at(-2));
Output

Click Run to see what this code prints.

Modifying Array Elements

Unlike strings, arrays are mutable. Existing elements can be replaced directly using their indexes.

Modify an Element
const languages = [
'HTML',
'CSS',
'Java'
];
languages[2] = 'JavaScript';
console.log(languages);
Output

Click Run to see what this code prints.

Arrays are Mutable
  • 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.

push()
const languages = [
'HTML',
'CSS'
];
const newLength =
languages.push('JavaScript');
console.log(languages);
console.log(newLength);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

push() returns the new array length, not the updated array, but this code logs that return value expecting to see the cart contents. Fix it so it logs the updated array joined as 'Pen, Book, Eraser'.

expected output: Pen, Book, Eraser

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length.

unshift()
const languages = [
'CSS',
'JavaScript'
];
languages.unshift('HTML');
console.log(languages);
Output

Click Run to see what this code prints.

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.

pop()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
const removed =
languages.pop();
console.log(removed);
console.log(languages);
Output

Click Run to see what this code prints.

shift()

The shift() method removes and returns the first element.

shift()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
const removed =
languages.shift();
console.log(removed);
console.log(languages);
Output

Click Run to see what this code prints.

Deleting Elements

The delete operator can remove an array property, but it leaves an empty slot and does not reduce the array length.

Avoid delete
const fruits = [
'Apple',
'Banana',
'Mango'
];
delete fruits[1];
console.log(fruits);
console.log(fruits.length);
Output

Click Run to see what this code prints.

Avoid delete for Arrays
  • 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.

Remove with splice()
const languages = [
'HTML',
'CSS',
'Java',
'JavaScript'
];
const removed =
languages.splice(2, 1);
console.log(removed);
console.log(languages);
Output

Click Run to see what this code prints.

Insert with splice()
const languages = [
'HTML',
'JavaScript'
];
languages.splice(
1,
0,
'CSS'
);
console.log(languages);
Output

Click Run to see what this code prints.

Replace with splice()
const languages = [
'HTML',
'Java',
'JavaScript'
];
languages.splice(
1,
1,
'CSS'
);
console.log(languages);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

This should replace only 'Java' with 'CSS' while keeping 'Python', but the deleteCount removes both elements. Fix the splice() call so it logs 'HTML, CSS, Python, JavaScript'.

expected output: HTML, CSS, Python, JavaScript

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.

slice()
const languages = [
'HTML',
'CSS',
'JavaScript',
'React'
];
const webBasics =
languages.slice(0, 3);
console.log(webBasics);
console.log(languages);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

webBasics should contain only the first two languages, but slice(0, 3) includes a third one. Fix the slice() call so it logs 'HTML, CSS'.

expected output: HTML, CSS
slice() vs splice()
Feature slice() splice()
--------------------------------------------------
Changes Original No Yes
Extract Elements Yes Yes
Remove Elements No Yes
Insert Elements No Yes
Replace Elements No Yes

Combining Arrays

Multiple arrays can be combined using concat() or spread syntax.

concat()

concat()
const frontend = [
'HTML',
'CSS'
];
const programming = [
'JavaScript',
'TypeScript'
];
const technologies =
frontend.concat(programming);
console.log(technologies);
Output

Click Run to see what this code prints.

Spread Operator

Spread syntax expands array elements and is commonly used to combine or copy arrays.

Combine with Spread
const frontend = [
'HTML',
'CSS'
];
const programming = [
'JavaScript',
'TypeScript'
];
const technologies = [
...frontend,
...programming
];
console.log(technologies);
Output

Click Run to see what this code prints.

Converting Arrays to Strings

Arrays can be converted into strings using toString() or join().

toString()

Array toString()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.toString()
);
Output

Click Run to see what this code prints.

join()

The join() method combines array elements using a custom separator.

join()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.join(' | ')
);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The languages should be joined using a pipe separator ' | ', but the code uses a hyphen instead. Fix it so it prints 'HTML | CSS | JavaScript'.

expected output: HTML | CSS | JavaScript

Searching Arrays

JavaScript provides several methods for finding values and matching elements.

indexOf()

indexOf()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.indexOf('CSS')
);
console.log(
languages.indexOf('Python')
);
Output

Click Run to see what this code prints.

lastIndexOf()

lastIndexOf()
const numbers = [
10,
20,
10,
30,
10
];
console.log(
numbers.lastIndexOf(10)
);
Output

Click Run to see what this code prints.

includes()

includes()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
console.log(
languages.includes('CSS')
);
console.log(
languages.includes('Python')
);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The check for 'CSS' should return true, but the lowercase 'css' does not match the stored value, since includes() is case-sensitive. Fix the search term so it prints true then true.

expected output: true true

find()

The find() method returns the first element that satisfies a condition.

find()
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);
Output

Click Run to see what this code prints.

findIndex()

The findIndex() method returns the index of the first matching element.

findIndex()
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);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

This should find the index of the product with id 3, but the condition compares against id 5, which does not exist. Fix the condition so it prints 2.

expected output: 2

findLast()

The findLast() method searches from the end and returns the first matching element encountered.

findLast()
const numbers = [
10,
25,
30,
45
];
const result =
numbers.findLast(
number => number > 20
);
console.log(result);
Output

Click Run to see what this code prints.

findLastIndex()

findLastIndex()
const numbers = [
10,
25,
30,
45
];
const index =
numbers.findLastIndex(
number => number > 20
);
console.log(index);
Output

Click Run to see what this code prints.

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.

some()
const ages = [
15,
17,
22,
14
];
const hasAdult =
ages.some(
age => age >= 18
);
console.log(hasAdult);
Output

Click Run to see what this code prints.

every()

The every() method returns true only when all elements satisfy the condition.

every()
const scores = [
75,
80,
90,
65
];
const allPassed =
scores.every(
score => score >= 40
);
console.log(allPassed);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The passing mark is 40, but this checks for 70, which makes the lowest score fail incorrectly. Fix the condition so allPassed prints true.

expected output: true

Iterating Arrays

Iteration means processing array elements one by one.

for Loop

Array for Loop
const languages = [
'HTML',
'CSS',
'JavaScript'
];
for (
let index = 0;
index < languages.length;
index++
) {
console.log(
index,
languages[index]
);
}
Output

Click Run to see what this code prints.

for...of Loop

for...of
const languages = [
'HTML',
'CSS',
'JavaScript'
];
for (const language of languages) {
console.log(language);
}
Output

Click Run to see what this code prints.

forEach()

The forEach() method executes a function once for every array element.

forEach()
const languages = [
'HTML',
'CSS',
'JavaScript'
];
languages.forEach(
function (language, index) {
console.log(
index,
language
);
}
);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The callback's parameters are named in the wrong order, so it logs the language before the index instead of the index before the language. Fix the parameter order so it logs '0 HTML', '1 CSS', '2 JavaScript'.

expected output: 0 HTML 1 CSS 2 JavaScript
forEach()
  • 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.

map()
const prices = [
100,
200,
300
];
const doubledPrices =
prices.map(
price => price * 2
);
console.log(prices);
console.log(doubledPrices);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The arrow function uses a block body but forgets to return the doubled price, so every value becomes undefined. Fix it so it logs '200, 400, 600'.

expected output: 200, 400, 600
Transform Objects
const users = [
{ name: 'Aarav', age: 25 },
{ name: 'Priya', age: 22 }
];
const names =
users.map(
user => user.name
);
console.log(names);
Output

Click Run to see what this code prints.

Filtering Arrays

Filtering creates a new array containing only elements that satisfy a condition.

filter()

filter()
const numbers = [
10,
25,
30,
45,
50
];
const largeNumbers =
numbers.filter(
number => number >= 30
);
console.log(largeNumbers);
Output

Click Run to see what this code prints.

Filter Products
const products = [
{
name: 'Laptop',
inStock: true
},
{
name: 'Phone',
inStock: false
},
{
name: 'Tablet',
inStock: true
}
];
const availableProducts =
products.filter(
product => product.inStock
);
console.log(availableProducts);
Output

Click Run to see what this code prints.

Reducing Arrays

Reduction processes all elements and combines them into a single result.

reduce()

Sum with reduce()
const prices = [
100,
200,
300
];
const total =
prices.reduce(
function (
accumulator,
price
) {
return accumulator + price;
},
0
);
console.log(total);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The reduce() call should start the accumulator at 0, but it starts at 100, adding 100 extra to the total. Fix the initial value so it prints 600.

expected output: 600
reduce() Flow
Array: [100, 200, 300]
Initial Accumulator = 0
Step 1:
0 + 100 = 100
Step 2:
100 + 200 = 300
Step 3:
300 + 300 = 600
Final Result:
600
Shopping Cart Total
const 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);
Output

Click Run to see what this code prints.

reduceRight()

The reduceRight() method works like reduce() but processes elements from right to left.

reduceRight()
const letters = [
'A',
'B',
'C'
];
const result =
letters.reduceRight(
(text, letter) =>
text + letter,
''
);
console.log(result);
Output

Click Run to see what this code prints.

Sorting Arrays

Sorting arranges elements into a particular order.

sort()

By default, sort() converts values to strings and compares them lexicographically.

Sort Strings
const fruits = [
'Mango',
'Apple',
'Banana'
];
fruits.sort();
console.log(fruits);
Output

Click Run to see what this code prints.

sort() Modifies the Original Array
  • 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

Wrong Numeric Sorting
const numbers = [
100,
5,
20,
3
];
numbers.sort();
console.log(numbers);
Output

Click Run to see what this code prints.

Ascending Numeric Sort
const numbers = [
100,
5,
20,
3
];
numbers.sort(
(a, b) => a - b
);
console.log(numbers);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

sort() without a compare function sorts numbers as strings, producing the wrong order. Fix the sort() call so it prints '5, 30, 40, 200'.

expected output: 5, 30, 40, 200
Descending Numeric Sort
const numbers = [
100,
5,
20,
3
];
numbers.sort(
(a, b) => b - a
);
console.log(numbers);
Output

Click Run to see what this code prints.

Sorting Objects

Sort Products by Price
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);
Output

Click Run to see what this code prints.

toSorted()

The toSorted() method returns a sorted copy without changing the original array.

toSorted()
const numbers = [
30,
10,
20
];
const sorted =
numbers.toSorted(
(a, b) => a - b
);
console.log(numbers);
console.log(sorted);
Output

Click Run to see what this code prints.

Reversing Arrays

Reversing changes the order of elements from end to beginning.

reverse()

reverse()
const numbers = [
1,
2,
3,
4
];
numbers.reverse();
console.log(numbers);
Output

Click Run to see what this code prints.

toReversed()

The toReversed() method returns a reversed copy without modifying the original array.

toReversed()
const numbers = [
1,
2,
3
];
const reversed =
numbers.toReversed();
console.log(numbers);
console.log(reversed);
Output

Click Run to see what this code prints.

Copying Arrays

Assigning an array to another variable does not create an independent copy. Both variables reference the same array.

Reference Copy
const original = [
'HTML',
'CSS'
];
const copy = original;
copy.push('JavaScript');
console.log(original);
console.log(copy);
Output

Click Run to see what this code prints.

Independent Shallow Copy
const original = [
'HTML',
'CSS'
];
const copy = [...original];
copy.push('JavaScript');
console.log(original);
console.log(copy);
Output

Click Run to see what this code prints.

Shallow Copies

Spread syntax, slice(), and Array.from() create shallow copies. Nested objects and arrays are still shared by reference.

Shallow Copy Behavior
const original = [
{
name: 'Aarav'
}
];
const copy = [...original];
copy[0].name = 'Priya';
console.log(original[0].name);
console.log(copy[0].name);
Output

Click Run to see what this code prints.

Array Destructuring

Array destructuring extracts values from an array into variables.

Array Destructuring
const languages = [
'HTML',
'CSS',
'JavaScript'
];
const [
first,
second,
third
] = languages;
console.log(first);
console.log(second);
console.log(third);
Output

Click Run to see what this code prints.

Mini Challenge · JavaScript

The destructured variable names are swapped, so first and second receive the wrong values. Fix the destructuring order so it logs HTML, CSS, JavaScript.

expected output: HTML CSS JavaScript

Skipping Elements

Skip Elements
const values = [
'A',
'B',
'C'
];
const [
first,
,
third
] = values;
console.log(first);
console.log(third);
Output

Click Run to see what this code prints.

Default Values

Destructuring Defaults
const colors = ['Red'];
const [
primary,
secondary = 'Blue'
] = colors;
console.log(primary);
console.log(secondary);
Output

Click Run to see what this code prints.

Rest Pattern

The rest pattern collects remaining elements into a new array.

Rest Pattern
const numbers = [
10,
20,
30,
40
];
const [
first,
...remaining
] = numbers;
console.log(first);
console.log(remaining);
Output

Click Run to see what this code prints.

Swapping Variables

Swap Variables
let first = 'A';
let second = 'B';
[
first,
second
] = [
second,
first
];
console.log(first);
console.log(second);
Output

Click Run to see what this code prints.

Nested Arrays

An array can contain other arrays as elements.

Nested Array
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.

Matrix
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix);
Matrix Structure
Column
0 1 2
Row 0 1 2 3
Row 1 4 5 6
Row 2 7 8 9

Accessing Nested Values

Nested Indexes
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]);
Output

Click Run to see what this code prints.

Flattening Arrays

Flattening converts nested arrays into a simpler array structure.

flat()

flat()
const nested = [
1,
[2, 3],
[4, 5]
];
const result =
nested.flat();
console.log(result);
Output

Click Run to see what this code prints.

Deep Flattening
const nested = [
1,
[2, [3, [4]]]
];
const result =
nested.flat(Infinity);
console.log(result);
Output

Click Run to see what this code prints.

flatMap()

The flatMap() method maps every element and then flattens the result by one level.

flatMap()
const sentences = [
'Learn JavaScript',
'Build Projects'
];
const words =
sentences.flatMap(
sentence =>
sentence.split(' ')
);
console.log(words);
Output

Click Run to see what this code prints.

Checking Arrays

Because arrays are objects, typeof cannot reliably distinguish arrays from other objects.

typeof Array
const values = [];
console.log(typeof values);
Output

Click Run to see what this code prints.

Array.isArray()

Array.isArray()
console.log(
Array.isArray([])
);
console.log(
Array.isArray({})
);
console.log(
Array.isArray('JavaScript')
);
Output

Click Run to see what this code prints.

Array References

Arrays are reference values. Variables store references to arrays rather than independent copies of their contents.

Shared Reference
const first = [
'HTML',
'CSS'
];
const second = first;
second.push('JavaScript');
console.log(first);
Output

Click Run to see what this code prints.

Comparing Arrays

Two different arrays are not equal even when they contain identical values because they have different references.

Array Comparison
const first = [1, 2, 3];
const second = [1, 2, 3];
const third = first;
console.log(first === second);
console.log(first === third);
Output

Click Run to see what this code prints.

Clearing Arrays

Clear with length
const items = [
'A',
'B',
'C'
];
items.length = 0;
console.log(items);
Output

Click Run to see what this code prints.

Reassign an Array
let items = [
'A',
'B',
'C'
];
items = [];
console.log(items);
Output

Click Run to see what this code prints.

Removing Duplicates

A Set stores unique values. Combining Set with spread syntax is a common way to remove primitive duplicates.

Remove Duplicates
const numbers = [
1,
2,
2,
3,
3,
4
];
const uniqueNumbers = [
...new Set(numbers)
];
console.log(uniqueNumbers);
Output

Click Run to see what this code prints.

Grouping Data

Arrays can be grouped into categories using reduce().

Group Products
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);
Output

Click Run to see what this code prints.

Common Array Patterns

Certain array-processing patterns appear repeatedly in real applications and programming problems.

Sum of Numbers

Calculate Sum
function calculateSum(numbers) {
return numbers.reduce(
(sum, number) =>
sum + number,
0
);
}
console.log(
calculateSum(
[10, 20, 30, 40]
)
);
Output

Click Run to see what this code prints.

Maximum and Minimum

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);
Output

Click Run to see what this code prints.

Count Occurrences

Count Values
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);
Output

Click Run to see what this code prints.

Unique Values

Get Unique Values
function getUniqueValues(values) {
return [...new Set(values)];
}
console.log(
getUniqueValues(
[1, 1, 2, 3, 3, 4]
)
);
Output

Click Run to see what this code prints.

Chunk an Array

Chunking divides a large array into smaller arrays of a specified size.

Chunk Array
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
)
);
Output

Click Run to see what this code prints.

Shuffle an Array

The Fisher-Yates algorithm can shuffle an array by swapping elements from the end toward the beginning.

Fisher-Yates Shuffle
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]
)
);
Possible Output

Click Run to see what this code prints.

Complete Array Example

The following example builds a product manager that uses arrays for storing, searching, filtering, sorting, adding, and removing products.

index.html
<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>
script.js
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();
Browser Output

Click Run to see what this code prints.

What This Example Demonstrates
  • 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

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

Avoid These 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.
Common Array Mistakes
// ❌ 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]
);
// false

Best 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

An array is an ordered collection of values stored inside a single variable.

An element is an individual value stored inside an array.

An index is the numeric position of an element.

JavaScript arrays begin at index 0.

The most common approach is array literal syntax using square brackets.

Both can create arrays, but array literals are simpler and avoid special behavior with a single numeric constructor argument.

It creates an array containing the values passed to it.

It creates an array from an iterable or array-like value.

An empty array is truthy.

Check whether array.length === 0.

Yes. JavaScript arrays can contain values of different types.

Use the length property.

The final normal index is array.length - 1.

Use array[0].

Use array.at(-1) or array[array.length - 1].

JavaScript returns undefined.

Yes. Array elements can be added, removed, and replaced.

Yes. const prevents reassignment of the variable but does not make the array immutable.

Use push().

Use unshift().

Use pop().

Use shift().

Usually no. It leaves an empty slot without reducing the array length.

It can insert, remove, or replace elements and modifies the original array.

It returns a shallow copy of part of an array without modifying the original.

slice() extracts without mutation, while splice() changes the original array.

Use concat() or spread syntax.

Use toString() or join().

join() allows you to choose the separator.

Use indexOf() for primitive values or findIndex() for condition-based searching.

It returns -1.

Use includes().

It returns the first matching element or undefined.

It returns a new array containing all matching elements.

find() returns one matching element, while filter() returns an array of all matches.

It returns true when at least one element satisfies a condition.

It returns true only when every element satisfies a condition.

Use a for loop, for...of loop, or array iteration method.

It returns undefined.

It creates a new array by transforming every element.

It creates a new array containing elements that pass a condition.

It combines array elements into a single result such as a total, object, or other accumulated value.

Providing an initial value is usually clearer and safer, especially for potentially empty arrays.

Default sorting compares values as strings.

Use array.sort((a, b) => a - b).

Use array.sort((a, b) => b - a).

Yes.

It returns a sorted copy without changing the original array.

Yes.

It returns a reversed copy without changing the original array.

Use spread syntax, slice(), or Array.from() for a shallow copy.

It creates a new outer array while nested objects and arrays remain shared references.

It extracts array elements into variables using a concise syntax.

Use the rest pattern.

Yes. Array destructuring provides a concise way to swap values.

It is an array containing another array.

It is an array structure with multiple levels, often used for rows and columns.

It creates a new array with nested arrays flattened to a specified depth.

It maps each element and then flattens the result by one level.

Arrays are specialized objects in JavaScript.

Use Array.isArray().

Separate arrays have different references.

A common approach is [...new Set(array)].

Use reduce() or a loop.

Use Math.max(...array).

Use Math.min(...array).

Loop through the array in steps and use slice() for each chunk.

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.

Lesson 17 Completed
  • 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.
Next Lesson →

JavaScript Objects