Skip to content
JavaScript arrays: how they work and common methods

9 Minutes

JavaScript arrays: how they work and common methods

Fix Bugs Faster! Log Collection Made Easy

Get started

A JavaScript array allows us to group related data like product names, user IDs, log entries, cart items, or API results. Arrays play a vital role in all kinds of user functions, from shopping carts to game scores.

However the sheer flexibility of JavaScript arrays can also cause mistakes around mutation, copying, sorting, and searching. Soo we’ve put together this post to show you:

  • How arrays work.
  • How to create and update them.
  • The cheats and tips that developers use most often.

What are JavaScript arrays?

A JavaScript array is an ordered list of values stored under a single variable. Couple of key things to note:

  • Each item in an array has an index, starting at 0.
  • Arrays can store strings, numbers, booleans, objects, other arrays, or a mix of different value types.

How JavaScript arrays work

JavaScript arrays store values in a specific order. That order matters because each value is accessed by its index.

Here is the basic flow:

  1. We create an array with one or more values.
  2. JavaScript stores each value at a numeric index.
  3. We read or update values using those indexes.
  4. We use built-in array methods to add, remove, search, copy, or transform items.

Arrays also have a length property. It tells us how many positions the array contains, not always how many meaningful values we filled on purpose.

const fruits = ["apple", "banana", "orange"];

console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3

Arrays are objects under the hood, but we usually treat them as ordered collections. That is what makes them ideal for lists, sequences, and repeated operations.

Diagram showing a JavaScript array with emoji values, numeric indexes starting at 0, array length of 5, and the relationship between the last index and array length.

How to create JavaScript arrays

Array literals, and why everyone uses them

The standard way to create arrays in JavaScript is using array literals [].

This approach is simple, predictable, and works consistently across all use cases. So why use anything else, right?

const fruits = ["apple", "banana", "orange"];
const numbers = [1, 2, 3, 4];
const mixed = ["apple", 3, true, { name: "Tom" }];

Array literals:

  • Are easier to read and write.
  • Always create real values (no empty slots).
  • Avoid unexpected behavior when iterating or transforming data.

In practice, this is how arrays are created in almost all JavaScript codebases.

The Array() constructor (and when to avoid it)

The second way to create arrays is using the Array() constructor, but it behaves inconsistently depending on how it’s used.

const arr = new Array(5);
console.log(arr); // [empty × 5]

There are a small number of scenarios where developers might reach for Array( ), such as:

  • Creating an array with a fixed length.
  • Generating arrays programmatically.

But when we feed it a single number, it creates empty slots instead of actual values. These slots are skipped by methods like map() and forEach(), which can lead to subtle bugs and unexpected behavior.

In most development cases, there is no practical advantage to using Array(), so it is best to use safer and more predictable alternatives like Array.from() or .fill().

Common JavaScript array operations

Here’s a very quick reference for the most common array operations you’ll run into day-to-day.

TaskMethod
Add item to endpush()
Add item to startunshift()
Remove last itempop()
Remove first itemshift()
Remove/replace by indexsplice()
Copy part of arrayslice()
Merge arraysconcat(), spread ...
Remove duplicatesnew Set() + spread
Check if emptyarray.length === 0
String → arraysplit()
Array → stringjoin()

How to use JavaScript arrays

Once we have created an array, most operations revolve around reading, modifying, and transforming its values.

In practice, JavaScript arrays are used to:

  • Store lists of data (e.g. users, products, logs)
  • Loop through items and render UI elements
  • Transform API responses before displaying them
  • Filter or search data based on conditions
  • Aggregate values (totals, counts, summaries)
  • Manage application state (especially in frontend frameworks)
  • Prepare and format data for output (sorting, joining, flattening)

These patterns cover most real-world use cases and map directly to the array methods covered below.

Access and update values in a JavaScript array: array[index], .at()

Use index access to read or overwrite a specific position in a JavaScript array.

const fruits = ["apple", "banana", "orange"];

// Access values by index (0-based)
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"

// Update value at a specific index
fruits[1] = "kiwi";

console.log(fruits); // ["apple", "kiwi", "orange"]

// Access last item safely (cleaner for dynamic arrays)
console.log(fruits.at(-1)); // "orange"
  • Indexing is zero-based
  • Direct assignment mutates the array
  • .at(-1) is safer than length - 1 for readability

Add and remove items in arrays: push(), pop(), shift(), unshift()

These methods control how elements are added or removed from a JavaScript array.

const fruits = ["apple", "banana"];

fruits.push("orange");   // add item to end
// ["apple", "banana", "orange"]

fruits.pop();            // remove last item
// ["apple", "banana"]

fruits.unshift("kiwi");  // add item to beginning
// ["kiwi", "apple", "banana"]

fruits.shift();          // remove first item
// ["apple", "banana"]
  • All of these mutate the original array
  • Common in stack (push/pop) and queue (shift/unshift) patterns

Copy vs modify arrays: slice() vs splice()

These two methods are often confused but serve completely different purposes.

const fruits = ["apple", "banana", "orange"];

// slice → returns a new array (non-mutating)
const copy = fruits.slice(1, 3);

console.log(copy);   // ["banana", "orange"]
console.log(fruits); // unchanged
const numbers = [1, 2, 3, 4];

// splice → modifies the original array
numbers.splice(1, 1); // remove 1 item at index 1
// [1, 3, 4]

numbers.splice(1, 0, 99); // insert 99 at index 1
// [1, 99, 3, 4]
  • slice() → safe, non-mutating copy
  • splice() → direct mutation (add/remove/replace)

Search and find values in arrays: includes(), indexOf(), find()

Use different methods depending on how complex the search is.

const fruits = ["apple", "banana"];

fruits.includes("banana"); // true (exists or not)
fruits.indexOf("banana");  // 1 (position)
const users = [
  { id: 1, active: false },
  { id: 2, active: true }
];

// Find first match based on condition
const activeUser = users.find(user => user.active);
// { id: 2, active: true }

// Find index instead of value
const activeIndex = users.findIndex(user => user.active);
// 1
  • includes() → boolean check
  • indexOf() → index position
  • find() → condition-based (best for objects)

Transform array data: map(), filter(), reduce()

These are the core methods for transforming data in JavaScript arrays.

const numbers = [1, 2, 3];

// map → transform each item
const doubled = numbers.map(n => n * 2);
// [2, 4, 6]
const numbers = [1, 2, 3, 4];

// filter → keep matching items
const even = numbers.filter(n => n % 2 === 0);
// [2, 4]
const numbers = [1, 2, 3];

// reduce → combine into a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 6
  • Do not mutate the original array
  • Return new arrays (or a single value with reduce())

Format and reshape arrays: sort(), join(), flat()

These methods help prepare array data for output or further processing.

const numbers = [1, 10, 5];

// Sort numbers correctly (default is string sort)
numbers.sort((a, b) => a - b);

console.log(numbers); // [1, 5, 10]
const fruits = ["apple", "banana"];

// Convert array to string
const text = fruits.join(", ");
// "apple, banana"
const nested = [1, [2, [3]]];

// Flatten nested arrays
const flat = nested.flat(2);

console.log(flat); // [1, 2, 3]
  • sort() mutates the array
  • join() and flat() return new values

Quick takeaway

Most JavaScript array operations fall into a few patterns:

  • Access → array[index], .at()
  • Modify → push(), splice()
  • Search → find(), includes()
  • Transform → map(), filter(), reduce()

Master these, and you cover most real-world JavaScript use cases.

JavaScript arrays example

Here is a small example that combines common JavaScript array methods in one flow:

const products = [
  { name: "Laptop", price: 1200, inStock: true },
  { name: "Mouse", price: 25, inStock: true },
  { name: "Keyboard", price: 80, inStock: false }
];

// Filter products in stock
const availableProducts = products.filter(product => product.inStock);

// Get product names
const productNames = availableProducts.map(product => product.name);

// Calculate total price
const totalPrice = availableProducts.reduce((sum, product) => sum + product.price, 0);

console.log(availableProducts);
// [
//   { name: "Laptop", price: 1200, inStock: true },
//   { name: "Mouse", price: 25, inStock: true }
// ]

console.log(productNames); // ["Laptop", "Mouse"]
console.log(totalPrice);   // 1225

This is where arrays become useful in real applications. We rarely use one method in isolation. Usually, we combine them to clean, search, display, or summarize data.

Common mistakes when using JavaScript arrays

The biggest array bugs usually come from small assumptions.

  • Using sort() without a compare function for numbers This causes incorrect numeric order.
  • Confusing slice() with splice() One copies, the other mutates.
  • Forgetting which methods change the original array push(), pop(), shift(), unshift(), splice(), sort(), and reverse() all mutate.
  • Using includes() with objects It checks reference equality, not deep equality.
  • Changing length manually without understanding the result This can truncate arrays or create empty slots.

When arrays behave strangely in UI code, state management is often the real culprit. One quiet mutation can ruin everyone’s afternoon.

Troubleshooting JavaScript arrays

Sometimes JavaScript arrays do not behave as expected.

Here are some common issues and fixes:

IssuePossible fix
Numbers sort incorrectly ([1, 10, 5] → [1, 10, 5])Use sort((a, b) => a - b) for numeric sorting
UI not updating after array change (React, Vue, etc.)Avoid mutating arrays directly; return a new array (map, spread)
map() or forEach() not running on arrayCheck for empty slots (e.g. new Array(5)) instead of real values
includes() returns false for objectsCompare properties or use find() instead of reference comparison
Duplicates not removed properlyUse new Set() + spread for primitive values
Original array changed unexpectedlyCheck if method mutates (push, splice, sort) vs returns new array
undefined values appear after resizing arrayAvoid manually changing array.length
Nested arrays not flattened as expectedUse flat() with correct depth
Data from API renders incorrectlyValidate array shape before mapping (Array.isArray())
Unexpected NaN in calculationsEnsure all values are numbers before using reduce()

When debugging array issues in production, it helps to log values before and after transformations. This makes it easier to spot exactly where data changes unexpectedly.

When those issues only appear on real devices or with real users, debugging becomes harder.

Bugfender lets you capture logs remotely and inspect array data directly from production environments, so you can trace issues without reproducing them locally.

Try Bugfender for free and debug faster: https://dashboard.bugfender.com/signup

FAQs about JavaScript arrays

Are JavaScript arrays objects?

Yes. Arrays are a specialized type of object in JavaScript. They are built for ordered collections and come with array-specific methods like map(), filter(), and push().

What is the difference between slice() and splice()?

slice() returns a new array and leaves the original unchanged. splice() changes the original array by removing, replacing, or inserting values.

Which JavaScript array methods mutate the original array?

Common mutating methods include push(), pop(), shift(), unshift(), splice(), sort(), and reverse().

How do we check if a JavaScript array is empty?

Use the length property:

const items = [];

console.log(items.length === 0); // true

What is the best way to remove duplicates from a JavaScript array?

For primitive values, new Set() is usually the simplest option.

const values = [1, 2, 2, 3];
const uniqueValues = [...new Set(values)];

Final thoughts on JavaScript arrays

JavaScript arrays are one of the most useful data structures in the language. We use them to store, search, transform, and display data in almost every kind of application.

The key to using arrays well is not memorizing every method. It is understanding how arrays work, which methods mutate data, and which methods return a new array.

Once we get that part right, array-heavy code becomes much easier to write, read, and debug.

Expect The Unexpected!

Debug Faster With Bugfender

Start for Free
blog author

Aleix Ventayol

Aleix Ventayol is CEO and co-founder of Bugfender, with 20 years' experience building apps and solutions for clients like AVG, Qustodio, Primavera Sound and Levi's. As a former CTO and full-stack developer, Aleix is passionate about building tools that solve the real problems of app development and help teams build better software.

Join thousands of developers
and start fixing bugs faster than ever.