Arrays in JavaScript

Learn Arrays in JavaScript with practical examples, explanations, best practices, and real-world coding techniques.

Arrays in JavaScript are ordered collections used to store multiple values in a single variable. Each element is associated with a numeric index, starting from 0, which allows elements to be accessed directly.

JavaScript arrays are dynamic, meaning their size can change as elements are added or removed. An array can contain values of different types, including numbers, strings, objects, functions, and even other arrays. Arrays are widely used in frontend applications, Node.js services, data processing, and algorithmic problem solving.

Creating an Array in JavaScript

The most common way to create an array is with an array literal using square brackets.

const languages = ["JavaScript", "Python", "Java"];

console.log(languages);

You can also create an empty array and add elements later.

const skills = [];

skills.push("JavaScript");
skills.push("TypeScript");
skills.push("Angular");

console.log(skills);

Accessing Array Elements

Array elements are accessed using their index. The first element has index 0, the second has index 1, and so on.

const languages = ["JavaScript", "Python", "Java"];

console.log(languages[0]);
console.log(languages[1]);
console.log(languages[2]);

JavaScript also provides at(), which can be useful when accessing elements from the end of an array.

const numbers = [10, 20, 30, 40];

console.log(numbers.at(-1));
console.log(numbers.at(-2));

Updating Array Elements

An existing element can be replaced by assigning a new value to its index.

const languages = ["JavaScript", "Python", "Java"];

languages[1] = "TypeScript";

console.log(languages);

Updating an existing index changes the value without changing the array's length.

Adding Elements to an Array

The push() method adds one or more elements to the end of an array.

const numbers = [10, 20, 30];

numbers.push(40);
numbers.push(50, 60);

console.log(numbers);

To add an element at the beginning, use unshift().

const numbers = [20, 30, 40];

numbers.unshift(10);

console.log(numbers);

Adding elements at the beginning or middle can require existing elements to be shifted, so these operations can be more expensive than appending to the end.

Removing Elements from an Array

The pop() method removes the last element and returns it.

const numbers = [10, 20, 30, 40];

const removed = numbers.pop();

console.log(removed);
console.log(numbers);

The shift() method removes the first element.

const numbers = [10, 20, 30, 40];

const removed = numbers.shift();

console.log(removed);
console.log(numbers);

Insert and Delete with splice()

The splice() method can insert, remove, or replace elements at a specific position.

Inserting Elements

const languages = ["JavaScript", "Java", "C#"];

languages.splice(1, 0, "Python");

console.log(languages);

The first argument specifies the starting index, the second specifies how many elements to remove, and additional arguments are inserted at that position.

Deleting Elements

const languages = ["JavaScript", "Python", "Java", "C#"];

languages.splice(1, 2);

console.log(languages);

Replacing Elements

const languages = ["JavaScript", "Python", "Java"];

languages.splice(1, 1, "TypeScript");

console.log(languages);

Finding the Length of an Array

The length property returns the number of elements in an array.

const users = ["Alice", "Bob", "Charlie"];

console.log(users.length);

The last valid index is usually length - 1.

Traversing an Array

A traditional for loop can be used when both the index and value are needed.

const languages = ["JavaScript", "Python", "Java"];

for (let i = 0; i < languages.length; i++) {
  console.log(i, languages[i]);
}

The for...of loop is useful when only the values are required.

for (const language of languages) {
  console.log(language);
}

Searching Arrays

JavaScript provides several methods for finding values in arrays. includes() checks whether a value exists, while indexOf() returns its index.

const languages = ["JavaScript", "Python", "Java"];

console.log(languages.includes("Python"));
console.log(languages.indexOf("Java"));
console.log(languages.indexOf("C#"));

When searching objects or values based on a condition, methods such as find() and findIndex() are useful.

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" }
];

const user = users.find(user => user.id === 2);
const index = users.findIndex(user => user.name === "Charlie");

console.log(user);
console.log(index);

Filtering Array Elements

The filter() method creates a new array containing elements that satisfy a condition.

const numbers = [10, 15, 20, 25, 30];

const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers);

Transforming Arrays with map()

The map() method creates a new array by transforming every element in the original array.

const prices = [100, 200, 300];

const discountedPrices = prices.map(
  price => price * 0.9
);

console.log(discountedPrices);

Unlike methods such as splice(), map() does not modify the original array.

Reducing an Array to One Value

The reduce() method processes elements and combines them into a single result. It is commonly used for totals, aggregation, grouping, and other calculations.

const prices = [100, 200, 300];

const total = prices.reduce(
  (sum, price) => sum + price,
  0
);

console.log(total);

Sorting JavaScript Arrays

The sort() method sorts an array in place. By default, JavaScript converts elements to strings for comparison, so a numeric comparator should be supplied when sorting numbers.

const numbers = [40, 10, 30, 20];

numbers.sort((a, b) => a - b);

console.log(numbers);

For descending order:

numbers.sort((a, b) => b - a);

console.log(numbers);

Reversing an Array

The reverse() method reverses the elements of the existing array in place.

const numbers = [10, 20, 30, 40];

numbers.reverse();

console.log(numbers);

When the original array should not be modified, create a copy before reversing it.

const numbers = [10, 20, 30, 40];

const reversed = [...numbers].reverse();

console.log(reversed);
console.log(numbers);

Copying and Combining Arrays

The spread syntax can create a shallow copy of an array and combine multiple arrays.

const frontend = ["HTML", "CSS", "JavaScript"];
const backend = ["Node.js", "Python"];

const technologies = [...frontend, ...backend];

console.log(technologies);

A spread copy is shallow. If the array contains objects or other nested arrays, those nested references are not deeply cloned.

Multidimensional Arrays

An array can contain other arrays, allowing JavaScript to represent matrices, grids, tables, and other multidimensional structures.

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[0][1]);
console.log(matrix[2][2]);

The first index selects the row and the second index selects the element within that row.

Array Destructuring

Array destructuring provides a convenient way to extract values into variables based on their positions.

const languages = ["JavaScript", "Python", "Java"];

const [first, second, third] = languages;

console.log(first);
console.log(second);
console.log(third);

Removing Duplicate Values

A Set can be combined with an array to create a collection containing only unique values.

const numbers = [10, 20, 10, 30, 20, 40];

const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);

Array Time Complexity

Understanding the approximate cost of common array operations is important when working with large datasets or designing algorithms.

Operation Typical Complexity
Access by index O(1)
push() O(1) amortized
pop() O(1)
unshift() O(n)
shift() O(n)
includes() O(n)
indexOf() O(n)
splice() O(n)
Full traversal O(n)

These are typical algorithmic expectations. Actual JavaScript engine behavior can vary, but the costs of shifting or scanning elements are important when reasoning about performance.

Arrays for Stack and Queue Operations

JavaScript arrays can be used to implement a stack because push() and pop() operate at the end of the array.

const stack = [];

stack.push("First");
stack.push("Second");
stack.push("Third");

console.log(stack.pop());
console.log(stack);

A simple queue can use push() and shift(), although repeated shift operations can become expensive for large queues.

Common Array Mistakes

  • Forgetting that array indexes start at zero.
  • Accessing an index outside the expected range.
  • Using sort() without a numeric comparator when sorting numbers.
  • Using shift() repeatedly for very large queues.
  • Confusing map() with forEach().
  • Assuming methods such as sort(), reverse(), and splice() always create new arrays.
  • Assuming spread syntax performs a deep copy of nested objects.
  • Using an Array for uniqueness checks when a Set would better represent the requirement.

When Should You Use Arrays?

Arrays are a good choice when data has an inherent order and elements need to be accessed, traversed, transformed, or processed as a sequence.

  • You need an ordered collection.
  • You need indexed access to elements.
  • The collection needs to grow or shrink dynamically.
  • You frequently iterate over the entire collection.
  • You need built-in methods for filtering, mapping, sorting, and reducing.
  • You are representing lists, grids, matrices, or sequences of data.

Practical Example: Processing User Scores

Arrays can be combined with methods such as filter(), map(), and reduce() to process application data.

const scores = [45, 78, 92, 61, 88];

const passingScores = scores.filter(
  score => score >= 60
);

const increasedScores = passingScores.map(
  score => score + 5
);

const total = increasedScores.reduce(
  (sum, score) => sum + score,
  0
);

console.log("Passing scores:", passingScores);
console.log("Updated scores:", increasedScores);
console.log("Total:", total);

Key Takeaways

  • JavaScript arrays are dynamic ordered collections.
  • Array indexes start at zero.
  • push() and pop() work at the end of an array.
  • shift() and unshift() operate at the beginning and can require shifting elements.
  • splice() can insert, remove, and replace elements.
  • map(), filter(), and reduce() are useful for data processing.
  • Use a numeric comparator with sort() when sorting numbers.
  • Arrays provide O(1) indexed access and typically O(n) linear searching.
  • Choose another structure such as Set or Map when its semantics better match the problem.

Code Examples

const languages = ["JavaScript", "Python", "Java"];

languages.push("C#");
languages[1] = "TypeScript";

console.log(languages);
    
const numbers = [10, 20, 40, 50];

numbers.splice(2, 0, 30);

console.log(numbers);

numbers.splice(1, 2);

console.log(numbers);
    
const numbers = [10, 15, 20, 25, 30];

const evenNumbers = numbers
  .filter(number => number % 2 === 0)
  .map(number => number * 2);

console.log(evenNumbers);
    
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" }
];

const user = users.find(user => user.id === 2);

console.log(user);
    
const numbers = [10, 20, 10, 30, 20, 40];

const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);
    

Pro Tip

Use arrays when your data is naturally ordered and indexed access or sequential processing is important. Prefer push() and pop() for stack-like operations, and consider Set or Map when uniqueness or key-based lookup is the primary requirement.

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.