JavaScript tutorials  /  Arrays in JavaScript
Chapter 6 · JavaScript

Arrays in JavaScript

An array in JavaScript is an ordered, list-like object used to store multiple values in a single variable, where each value (called an element) can be accessed using a numeric index starting from zero.

An array is like a container that can hold multiple pieces of data together in a specific order, instead of creating separate variables for each value. You can access, add, remove, or modify individual items in an array using their position (index), and JavaScript provides many built-in methods to work with arrays efficiently.

Think of a to-do list app on your phone. Instead of storing each task in a completely separate note, all your tasks are kept together in one ordered list, where you can add a new task to the end, remove a completed one, or check the task at a specific position. Similarly, in a music streaming app, a playlist is essentially an array of song objects, where each song has properties like title, artist, and duration, and the app can loop through this array to display the playlist, shuffle it, or calculate the total playback time. In code, this is represented using a JavaScript array like ['Song A', 'Song B', 'Song C'], which can be manipulated using array methods.

Arrays are essential because most real-world applications deal with collections of related data, such as a list of products in a shopping cart, user comments on a post, or search results from an API. Without arrays, developers would need to create individually named variables for every single item, which becomes unmanageable when the number of items is large or unknown in advance. Arrays provide an ordered, indexed structure along with powerful built-in methods (like map, filter, and reduce) that make it easy to loop through, transform, search, and manipulate collections of data efficiently.

  • Array Literal Notation: The most common and recommended way to create an array in JavaScript, using square brackets [] with comma-separated values, such as const fruits = ['Apple', 'Banana', 'Mango'].
  • Array Constructor Notation: Creating an array using the 'new Array()' constructor, which can be used to create an empty array, an array with specific elements, or an array with a predefined length, though it is generally less preferred than literal notation due to potential ambiguity with a single numeric argument.
  • Multidimensional Arrays (Arrays of Arrays): An array whose elements are themselves arrays, commonly used to represent grid-like or matrix-like data structures, such as a 2D board in a game or tabular data with rows and columns.
  • Array of Objects: An array where each element is an object containing multiple related properties, commonly used to represent structured data like a list of users, products, or records, such as [{name: 'Amit', age: 25}, {name: 'Priya', age: 30}].
  • Sparse Arrays: An array that contains gaps or missing elements at certain indices, often created by explicitly setting an array's length beyond its current number of elements or by deleting an element without adjusting subsequent indices, resulting in 'empty' slots.
// Creating an array const arrayName = [element1, element2, element3]; // Accessing an element arrayName[index]; // Modifying an element arrayName[index] = newValue; // Common array methods arrayName.push(value); // add to end arrayName.pop(); // remove from end arrayName.map(callback); // transform each element arrayName.filter(callback); // filter elements arrayName.reduce(callback, initialValue); // accumulate a value
Suppose you are building an online store's product listing page where you need to display a dynamic number of products fetched from an API, calculate the total price of all products currently in stock, and filter out products that are out of stock, all without knowing in advance how many products there will be. Storing each product in a separate variable is impossible since the count is dynamic. Arrays solve this by letting you store all product objects in a single ordered collection, then use built-in array methods like filter() and reduce() to efficiently process the entire collection based on your requirements.
Creating and Accessing Array Elements
Demonstrates basic array creation, accessing elements by index, and finding the length of an array.
JavaScript
const fruits = ["Apple", "Banana", "Mango", "Orange"]; console.log("First fruit:", fruits[0]); console.log("Last fruit:", fruits[fruits.length - 1]); console.log("Total fruits:", fruits.length); fruits[1] = "Grapes"; console.log("Updated array:", fruits);
First fruit: Apple Last fruit: Orange Total fruits: 4 Updated array: [ 'Apple', 'Grapes', 'Mango', 'Orange' ]
Array elements are accessed using zero-based indices, so fruits[0] gives the first element. fruits.length gives the total count of elements, and fruits[fruits.length - 1] retrieves the last element. Elements can be modified directly by assigning a new value to a specific index.
Adding and Removing Elements with push, pop, shift, and unshift
Demonstrates the four fundamental methods for adding and removing elements from the beginning or end of an array.
JavaScript
const numbers = [2, 3, 4]; numbers.push(5); console.log("After push:", numbers); numbers.pop(); console.log("After pop:", numbers); numbers.unshift(1); console.log("After unshift:", numbers); numbers.shift(); console.log("After shift:", numbers);
After push: [ 2, 3, 4, 5 ] After pop: [ 2, 3, 4 ] After unshift: [ 1, 2, 3, 4 ] After shift: [ 2, 3, 4 ]
push() adds an element to the end, pop() removes the last element, unshift() adds an element to the beginning, and shift() removes the first element. Each of these methods modifies the original array in place.
Transforming and Filtering Arrays with map and filter
Demonstrates using map() to transform each element in an array and filter() to select only elements that meet a specific condition.
JavaScript
const products = [ { name: "Laptop", price: 55000, inStock: true }, { name: "Mouse", price: 500, inStock: false }, { name: "Keyboard", price: 1200, inStock: true } ]; const availableProducts = products.filter(product => product.inStock); console.log("Available products:", availableProducts.map(p => p.name)); const discountedPrices = products.map(product => product.price * 0.9); console.log("Discounted prices:", discountedPrices);
Available products: [ 'Laptop', 'Keyboard' ] Discounted prices: [ 49500, 450, 1080 ]
filter() creates a new array containing only the products where inStock is true, using the condition as a callback. map() creates a new array by applying the discount calculation to every product's price, regardless of stock status. Neither method modifies the original products array.
Calculating a Total with reduce
Demonstrates using the reduce() method to accumulate all array values into a single total.
JavaScript
const cartPrices = [1200, 350, 899, 2100]; const total = cartPrices.reduce((accumulator, currentPrice) => { return accumulator + currentPrice; }, 0); console.log("Cart total:", total);
Cart total: 4549
reduce() takes a callback function and an initial accumulator value (0 in this case). On each iteration, it adds the current element to the accumulator and returns the updated value, which becomes the accumulator for the next iteration, ultimately producing a single summed total after processing all elements.
  • Confusing Array Index with Array Length: Beginners often try to access the last element using arrayName[arrayName.length] instead of arrayName[arrayName.length - 1], since array indices are zero-based, meaning the last valid index is always one less than the total length, causing an off-by-one error that returns undefined.
  • Using for...in to Loop Through Arrays: Using a for...in loop on an array iterates over its indices as strings (and any additional enumerable properties), rather than the values directly, which can lead to unexpected behavior. A for...of loop, forEach(), or a traditional for loop should be used instead when iterating over array elements.
  • Assuming map(), filter(), and similar methods Modify the Original Array: Methods like map(), filter(), slice(), and concat() return a brand new array and do not modify the original array. Developers sometimes mistakenly call these methods expecting the original array to change, when in fact they need to store the returned result in a new variable or reassign it.
  • Using delete to Remove an Array Element: Using the delete operator on an array element (e.g., delete arr[2]) removes the value but leaves an empty slot (undefined) at that index, without shifting subsequent elements or updating the array's length, resulting in a sparse array. splice() should be used instead to properly remove an element and adjust the array.
  • Comparing Arrays Directly with === or ==: Attempting to compare two arrays for equality using === or == (e.g., [1,2,3] === [1,2,3]) always returns false, even if they contain identical elements, because arrays are reference types and these operators compare memory references, not content. Proper array content comparison requires iterating through elements or using methods like JSON.stringify() (with caveats) or a dedicated deep-equality check.
  • Use Array Literal Notation Instead of the Array Constructor: Prefer creating arrays with square bracket literal notation (const arr = [1, 2, 3]) instead of 'new Array()', since literal notation is more concise, readable, and avoids the ambiguous behavior of new Array(n), which creates an empty array of length n rather than an array containing the single number n.
  • Use const for Arrays That Won't Be Reassigned: Declare arrays with const instead of let or var when the array reference itself will not be reassigned to a completely new array, since const still allows the array's contents to be modified (via push, pop, etc.) while preventing accidental reassignment of the variable to a different array.
  • Prefer Non-Mutating Methods for Predictable Data Flow: When possible, prefer array methods that return a new array (map, filter, slice, concat) over mutating methods (push, splice, sort) especially in applications using frameworks like React, where predictable, immutable data updates are important for correct rendering and state management.
  • Use Array.isArray() to Check if a Value Is Truly an Array: Use Array.isArray(value) instead of typeof value === 'object' to reliably check whether a value is an array, since typeof returns 'object' for both arrays and plain objects, making it unreliable for this specific check.
  • Use splice() for Precise Insertion or Removal of Elements: Use the splice() method when you need to add or remove elements at a specific position within an array (not just the beginning or end), since it provides fine-grained control over which elements are removed and what new elements are inserted, all in a single method call.
What is the difference between the map() and forEach() array methods in JavaScript?
map() creates and returns a new array containing the results of calling a provided function on every element of the original array, making it suitable when you need a transformed array as output. forEach() simply executes a provided function once for each array element but does not return a new array (it returns undefined), making it suitable for performing side effects like logging or updating external state, without needing a transformed result.
What is the difference between slice() and splice() in JavaScript arrays?
slice() returns a shallow copy of a portion of an array into a new array, based on start and end indices, without modifying the original array. splice() changes the contents of the original array by removing, replacing, or adding elements in place, and it returns an array containing any removed elements. The key difference is that slice() is non-mutating while splice() directly mutates the original array.
How does the reduce() method work, and can you give an example of a practical use case beyond summing numbers?
reduce() executes a reducer callback function on each element of the array, accumulating a single result based on the return value of the previous callback invocation, starting from an optional initial value. Beyond summing numbers, reduce() can be used for practical tasks like flattening a nested array, counting occurrences of values in an array, grouping objects by a property, or transforming an array into an object, since it can build any type of accumulated result, not just numbers.
Why does comparing two arrays with identical elements using === return false in JavaScript?
Arrays are reference types in JavaScript, meaning variables holding arrays store a reference (memory address) to the array object, not the actual array data itself. The === operator compares these references, not the contents, so two separately created arrays with identical elements will always be considered unequal since they point to different locations in memory, even though their contents look the same.
What are some ways to remove duplicate values from a JavaScript array?
A common modern approach is to convert the array into a Set (which automatically only stores unique values) and then spread it back into a new array, like [...new Set(array)]. Alternatively, you can use the filter() method combined with indexOf() to keep only the first occurrence of each value, or use reduce() to build a new array while checking for duplicates manually. The Set-based approach is generally the most concise and efficient for arrays of primitive values.
What is the difference between a shallow copy and a deep copy of an array, and how would you create each?
A shallow copy duplicates only the top-level elements of an array; if the array contains nested objects or arrays, both the original and the copy still reference the same nested objects, so modifying a nested object in one affects the other. Shallow copies can be created using the spread operator ([...array]), slice(), or Array.from(). A deep copy duplicates all nested levels completely, creating fully independent objects at every level, which can be achieved using structuredClone(array) in modern JavaScript, or through recursive copying or JSON.parse(JSON.stringify(array)) (with limitations for non-JSON-safe values like functions or undefined).
Write a JavaScript function 'findMax' that takes an array of numbers and returns the largest number in the array using a loop (without using Math.max).
function findMax(numbers) { let max = numbers[0]; for (let i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } return max; } console.log(findMax([3, 7, 2, 9, 4]));
Given an array of student objects with 'name' and 'score' properties, write a function that uses filter() and map() to return an array of names of students who scored 50 or above.
function getPassingStudentNames(students) { return students .filter(student => student.score >= 50) .map(student => student.name); } const students = [ { name: "Amit", score: 45 }, { name: "Sneha", score: 78 }, { name: "Rahul", score: 60 } ]; console.log(getPassingStudentNames(students));
Write a function 'groupByCategory' that takes an array of product objects (each with 'name' and 'category' properties) and uses reduce() to group them into an object where each key is a category and the value is an array of product names in that category.
function groupByCategory(products) { return products.reduce((groups, product) => { if (!groups[product.category]) { groups[product.category] = []; } groups[product.category].push(product.name); return groups; }, {}); } const products = [ { name: "Laptop", category: "Electronics" }, { name: "Shirt", category: "Clothing" }, { name: "Phone", category: "Electronics" }, { name: "Jeans", category: "Clothing" } ]; console.log(groupByCategory(products));

Arrays in JavaScript are ordered, indexed collections used to store multiple values in a single variable, forming the backbone of working with lists of data such as products, users, or search results. JavaScript provides powerful built-in methods like push, pop, map, filter, and reduce to add, remove, transform, and process array elements efficiently. Understanding the difference between mutating methods (like push and splice) and non-mutating methods (like map and slice), along with proper iteration techniques, is essential for writing predictable and bug-free JavaScript code.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.