LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Arrays in JavaScript – Methods and Operations

An array is a collection that stores multiple values in a single variable. For example, instead of creating separate variables for five student names, we can store all five names in one array.

Arrays in JavaScript – Methods and Operations

Quick Answer: An array stores multiple values in one variable. JavaScript provides methods to add, remove, search, sort, copy and transform array items. You can also process arrays using methods like map(), filter() and reduce().

1. What Is an Array in JavaScript?

Imagine you manage a grocery shop in Bengaluru. Customers place orders throughout the day. Each order contains several products.

How will you store and manage those products? Will you create a separate variable for every product?

An array solves this problem. It keeps related values together in one ordered collection.

Array = a collection that stores multiple values in one variable.

2. The Problem: Managing Products Without Arrays

Suppose Ravi manages a grocery shop. Three customers order different products. He stores every product in a separate variable.

Example 1: Store grocery products using separate variables

const product1 = "Rice";
const product2 = "Milk";
const product3 = "Bread";

console.log(product1);
console.log(product2);
console.log(product3);

Expected output

Rice
Milk
Bread

This works, but it becomes difficult to manage many products.

What goes wrong as the shop grows?

  1. We need a new variable for every product.
  2. We cannot easily process all products together.
  3. Searching for one product needs repeated checks.
  4. Adding or removing products makes the code longer.

Now imagine the shop handles 1,000 orders every day. Managing separate variables becomes impractical.

The Solution: Store Products in an Array

We can keep all product names inside one array. Each product gets an index.

Example 2: Store grocery products in an array

const products = ["Rice", "Milk", "Bread"];

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

Expected output

[ 'Rice', 'Milk', 'Bread' ]
Rice
Milk
Bread

One variable now stores all three products. We can access each product using its index.

See how an array stores products

Array memory view – Grocery products

Each position has an index. JavaScript arrays start at index zero.

Index 0Rice
Index 1Milk
Index 2Bread
Index 3Empty
Index 4Empty
1
Start with the first itemRice is stored at index 0.
2
Move to the next positionMilk is stored at index 1.
3
Read the third itemBread is stored at index 2.

The highlighted position changes automatically to explain zero-based indexing.

Separate variables compared with an array
Without an array With an array
One variable for each product. One variable stores all products.
Repeated code to process items. Loops can process every item.
Adding items needs more variables. Methods can add or remove items.
Searching requires repeated checks. Search methods can find items.

Important array terms

  • Array = a collection of values.
  • Element = one value inside an array.
  • Index = the position of an element.
  • Length = the number of elements.
  • Zero-based indexing = the first element uses index 0.
  • Method = a function that performs an operation.

3. Creating and Accessing Arrays

JavaScript offers several ways to create arrays. Array literals are the most common choice.

Example 3: Create arrays and read their values

const products = ["Rice", "Milk", "Bread"];

console.log(products[0]);
console.log(products[2]);
console.log(products.length);

const emptyProducts = [];
console.log(emptyProducts.length);

Expected output

Rice
Bread
3
0

Access the last element

Use length - 1 to find the last valid index.

Example 4: Read the last product

const products = ["Rice", "Milk", "Bread"];

console.log(products[products.length - 1]);

Expected output

Bread

Remember: An array with three items has indexes 0, 1 and 2. Its length is 3, but its last index is 2.

4. Adding and Removing Array Elements

Grocery orders change throughout the day. Customers add products and sometimes cancel them.

JavaScript provides methods for these operations. Some methods change the original array.

4.1 push() – Add an item at the end

push() adds one or more items to the end. It returns the new length.

Example 5: Add a product

const products = ["Rice", "Milk"];

const newLength = products.push("Bread");

console.log(products);
console.log(newLength);

Expected output

[ 'Rice', 'Milk', 'Bread' ]
3

4.2 pop() – Remove the last item

pop() removes the last item. It returns the removed value.

Example 6: Remove the last product

const products = ["Rice", "Milk", "Bread"];

const removedProduct = products.pop();

console.log(removedProduct);
console.log(products);

Expected output

Bread
[ 'Rice', 'Milk' ]

4.3 unshift() – Add an item at the beginning

unshift() adds items at the beginning. Existing indexes move forward.

Example 7: Add a priority product

const products = ["Milk", "Bread"];

products.unshift("Rice");

console.log(products);

Expected output

[ 'Rice', 'Milk', 'Bread' ]

4.4 shift() – Remove the first item

shift() removes the first item. It returns the removed value.

Example 8: Remove the first product

const products = ["Rice", "Milk", "Bread"];

const removedProduct = products.shift();

console.log(removedProduct);
console.log(products);

Expected output

Rice
[ 'Milk', 'Bread' ]

4.5 splice() – Add, remove or replace items

splice() changes an array at a chosen position.

It accepts a starting index, a delete count and optional new items.

Example 9: Replace a product

const products = ["Rice", "Milk", "Bread"];

products.splice(1, 1, "Butter");

console.log(products);

Expected output

[ 'Rice', 'Butter', 'Bread' ]

4.6 Watch how array updates work

Grocery basket – Array update workflow

Each operation changes the basket in a different way.

1
Initial basket[ Rice, Milk ]
 
2
push("Bread")[ Rice, Milk, Bread ] — adds at the end.
 
3
shift()[ Milk, Bread ] — removes the first item.
 
4
splice(1, 1, "Butter")[ Milk, Butter ] — replaces the item at index 1.

The workflow highlights each basket update in order. The examples show the result after each operation.

Array methods for adding and removing items
Method Operation Changes original?
push() Add at the end. Yes
pop() Remove from the end. Yes
unshift() Add at the beginning. Yes
shift() Remove from the beginning. Yes
splice() Add, remove or replace. Yes

5. Searching for Array Elements

Customers may ask whether a product is available. We can search the array.

5.1 includes() – Check whether a value exists

includes() returns true when the value exists. Otherwise, it returns false.

Example 10: Check product availability

const products = ["Rice", "Milk", "Bread"];

console.log(products.includes("Milk"));
console.log(products.includes("Coffee"));

Expected output

true
false

5.2 indexOf() – Find the first matching index

indexOf() returns the first matching index. It returns -1 when no match exists.

Example 11: Find a product position

const products = ["Rice", "Milk", "Bread"];

console.log(products.indexOf("Bread"));
console.log(products.indexOf("Coffee"));

Expected output

2
-1

5.3 find() – Find the first matching object

Real orders often contain product names, prices and quantities. We can store these details as objects.

Object = a value that groups related information using properties.

Example 12: Find a product by its name

const products = [
  { name: "Rice", price: 60 },
  { name: "Milk", price: 30 },
  { name: "Bread", price: 40 }
];

const product = products.find(item => item.name === "Milk");

console.log(product);

Expected output

{ name: 'Milk', price: 30 }

5.4 findIndex() – Find the index of a matching object

Example 13: Find the position of a product

const products = [
  { name: "Rice", price: 60 },
  { name: "Milk", price: 30 },
  { name: "Bread", price: 40 }
];

const index = products.findIndex(item => item.name === "Bread");

console.log(index);

Expected output

2

6. Transforming and Filtering Arrays

Many applications need to calculate totals or show selected products. JavaScript provides powerful methods for this work.

6.1 forEach() – Run an operation for every item

forEach() runs a callback for each array element. It does not create a new array.

Example 14: Print every grocery product

const products = ["Rice", "Milk", "Bread"];

products.forEach((product, index) => {
  console.log(index, product);
});

Expected output

0 Rice
1 Milk
2 Bread

6.2 map() – Create a new array

map() transforms every item. It returns a new array with the results.

Example 15: Get product prices

const products = [
  { name: "Rice", price: 60 },
  { name: "Milk", price: 30 },
  { name: "Bread", price: 40 }
];

const prices = products.map(product => product.price);

console.log(prices);

Expected output

[ 60, 30, 40 ]

6.3 filter() – Select matching items

filter() returns a new array with items that pass a condition.

Example 16: Find products priced above 35

const products = [
  { name: "Rice", price: 60 },
  { name: "Milk", price: 30 },
  { name: "Bread", price: 40 }
];

const selected = products.filter(product => product.price > 35);

console.log(selected);

Expected output

[
  { name: 'Rice', price: 60 },
  { name: 'Bread', price: 40 }
]

6.4 reduce() – Calculate one final value

reduce() processes all items and builds one final result. It is useful for totals.

Example 17: Calculate the total product value

const products = [
  { name: "Rice", price: 60 },
  { name: "Milk", price: 30 },
  { name: "Bread", price: 40 }
];

const total = products.reduce((sum, product) => {
  return sum + product.price;
}, 0);

console.log(total);

Expected output

130

6.5 See the array processing pipeline

Grocery data – Transform and calculate

Three separate operations process the same product collection.

1
Original product objectsRice: 60 · Milk: 30 · Bread: 40
 
2
map() – Select prices[60, 30, 40]
 
3
filter() – Keep prices above 35[60, 40]
 
4
reduce() – Calculate the total60 + 30 + 40 = 130

The animation explains how array methods select, transform and calculate product data.

Important: These methods have different purposes. map() transforms, filter() selects, and reduce() combines values. Each returns a new result and leaves the original array unchanged.

7. Sorting and Reversing Arrays

7.1 sort() – Arrange array elements

sort() changes the original array. By default, it sorts values as strings.

Use a comparison function when sorting numbers.

Example 18: Sort product prices from low to high

const prices = [60, 30, 100, 40];

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

console.log(prices);

Expected output

[ 30, 40, 60, 100 ]

Use b - a to sort numbers from high to low.

Example 19: Sort product prices from high to low

const prices = [60, 30, 100, 40];

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

console.log(prices);

Expected output

[ 100, 60, 40, 30 ]

7.2 reverse() – Reverse the element order

reverse() reverses the array in place. It changes the original array.

Example 20: Reverse the product list

const products = ["Rice", "Milk", "Bread"];

products.reverse();

console.log(products);

Expected output

[ 'Bread', 'Milk', 'Rice' ]

8. Copying and Combining Arrays

8.1 slice() – Copy part of an array

slice() returns selected elements in a new array. It does not change the original.

The ending index is not included.

Example 21: Copy selected products

const products = ["Rice", "Milk", "Bread", "Butter"];

const selected = products.slice(1, 3);

console.log(selected);
console.log(products);

Expected output

[ 'Milk', 'Bread' ]
[ 'Rice', 'Milk', 'Bread', 'Butter' ]

8.2 concat() – Combine arrays

concat() combines arrays and returns a new array.

Example 22: Combine two grocery lists

const morningProducts = ["Milk", "Bread"];
const eveningProducts = ["Rice", "Butter"];

const allProducts = morningProducts.concat(eveningProducts);

console.log(allProducts);

Expected output

[ 'Milk', 'Bread', 'Rice', 'Butter' ]

8.3 join() – Convert array elements into a string

join() combines elements into one string. You can provide a separator.

Example 23: Create a product summary

const products = ["Rice", "Milk", "Bread"];

const summary = products.join(", ");

console.log(summary);

Expected output

Rice, Milk, Bread

8.4 flat() – Flatten nested arrays

flat() creates a new array from nested arrays. Its default depth is one.

Example 24: Combine nested product lists

const productGroups = [
  ["Rice", "Milk"],
  ["Bread", "Butter"]
];

const products = productGroups.flat();

console.log(products);

Expected output

[ 'Rice', 'Milk', 'Bread', 'Butter' ]

9. Non-Mutating Array Methods

Some methods change the original array. Others return a new array or value.

Mutation = changing the existing array or object.

Knowing this difference helps prevent unexpected changes in applications.

Common array methods and their behavior
Method Changes original? Returns
push() Yes New length
pop() Yes Removed item
shift() Yes Removed item
unshift() Yes New length
splice() Yes Removed items
sort() Yes Sorted array
reverse() Yes Reversed array
slice() No New array
concat() No New array
map() No New array
filter() No New array
flat() No New array
reduce() No Accumulated result

Use spread syntax to make a shallow copy

The spread syntax copies the array's elements into a new array. This is a shallow copy.

Example 25: Copy an array before sorting

const prices = [60, 30, 100];

const sortedPrices = [...prices].sort((a, b) => a - b);

console.log(prices);
console.log(sortedPrices);

Expected output

[ 60, 30, 100 ]
[ 30, 60, 100 ]

Important: A shallow copy creates a new outer array. Nested objects are still shared references. Copy nested data separately when you need independent objects.

10. Useful Array Properties and Modern Methods

10.1 at() – Read an element by position

at() reads an element using a positive or negative index. Negative indexes count from the end.

Example 26: Read the last product with at()

const products = ["Rice", "Milk", "Bread"];

console.log(products.at(0));
console.log(products.at(-1));

Expected output

Rice
Bread

10.2 some() – Check whether at least one item matches

some() returns true when at least one item passes the condition.

Example 27: Check for an expensive product

const prices = [30, 40, 100];

const hasExpensiveProduct = prices.some(price => price > 80);

console.log(hasExpensiveProduct);

Expected output

true

10.3 every() – Check whether all items match

every() returns true only when every item passes the condition.

Example 28: Check whether all prices are positive

const prices = [30, 40, 100];

const allPricesValid = prices.every(price => price > 0);

console.log(allPricesValid);

Expected output

true

10.4 Array.isArray() – Check whether a value is an array

Example 29: Check a variable's type

const products = ["Rice", "Milk"];
const productName = "Bread";

console.log(Array.isArray(products));
console.log(Array.isArray(productName));

Expected output

true
false

11. A Practical Grocery Order Example

Now combine several array methods in one small application. Ravi needs a product summary for a customer.

The application must select available products, calculate the total and display the names.

Example 30: Process a grocery order

const order = [
  { name: "Rice", price: 60, available: true },
  { name: "Milk", price: 30, available: true },
  { name: "Bread", price: 40, available: false },
  { name: "Butter", price: 50, available: true }
];

const availableProducts = order.filter(
  product => product.available
);

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

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

console.log(productNames);
console.log(total);

Expected output

[ 'Rice', 'Milk', 'Butter' ]
140

How does this application work?

  1. filter() selects available products.
  2. reduce() adds their prices.
  3. map() creates a list of product names.
  4. console.log() displays the final results.

12. Common Array Mistakes and Best Practices

Mistake 1: Using an invalid index

JavaScript returns undefined when an index does not exist.

Wrong approach

const products = ["Rice", "Milk"];

console.log(products[5]);

Expected output

undefined

Better approach: Check the index before reading the value.

Corrected approach

const products = ["Rice", "Milk"];
const index = 5;

if (index >= 0 && index < products.length) {
  console.log(products[index]);
} else {
  console.log("Product not found");
}

Expected output

Product not found

Mistake 2: Sorting numbers without a comparator

Default sorting compares string representations. It may produce unexpected numeric order.

Wrong approach

const prices = [100, 30, 5];

prices.sort();

console.log(prices);

Expected output

[ 100, 30, 5 ]

Better approach: Supply a numeric comparison function.

Corrected approach

const prices = [100, 30, 5];

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

console.log(prices);

Expected output

[ 5, 30, 100 ]

Mistake 3: Confusing slice() and splice()

slice() copies a portion. splice() changes the original array.

Mistake 4: Changing an array while looping

Removing elements during iteration can skip items. Create a filtered array when possible.

Better approach: Filter unwanted products

const products = ["Rice", "Milk", "Bread"];

const remainingProducts = products.filter(
  product => product !== "Milk"
);

console.log(remainingProducts);

Expected output

[ 'Rice', 'Bread' ]

Best practices

  • Use const when you do not reassign the array variable.
  • Remember that const does not make array contents immutable.
  • Use map() when you need a transformed array.
  • Use filter() when you need selected elements.
  • Use reduce() when you need one accumulated result.
  • Use a comparator when sorting numbers.
  • Make a copy before changing data that must stay unchanged.
  • Check external data before using it as an array.

13. Array Performance and Real-World Trade-Offs

Array methods make code easier to read. However, different operations have different costs.

  • Reading an element by index is generally very fast.
  • Adding at the end is usually efficient.
  • Adding or removing at the beginning shifts other indexes.
  • Searching with find() may inspect many elements.
  • Sorting usually takes more work than a simple array traversal.

For small and medium collections, readable array methods are often a good choice. For very large datasets, measure performance with realistic data before changing the design.

Architect note: JavaScript arrays are ordered collections. They are not the best choice for every lookup pattern. A Map or Set may be a better fit when your data needs different access rules.

14. How Arrays Come Up in Interviews

Question 1: What is an array in JavaScript?

What the interviewer wants: They want to know whether you understand ordered collections and indexes.

Strong answer: "An array stores multiple values in one variable. Each element has an index, starting from zero. We can use array methods to add, remove, search and transform elements."

Question 2: What is the difference between map() and forEach()?

Strong answer: "Both run a callback for each element. But map returns a new array containing the callback results. forEach does not return a transformed array. I use map when I need new data."

Question 3: What is the difference between slice() and splice()?

Strong answer: "slice returns a selected portion in a new array. It does not change the original. splice can add, remove or replace elements. It changes the original array."

Question 4: Does sort() change the original array?

Strong answer: "Yes. sort changes the original array. For numeric values, I pass a comparison function. If I need to keep the original order, I copy the array before sorting."

Question 5: What is the difference between find() and filter()?

Strong answer: "find returns the first matching element. filter returns a new array containing every matching element. I choose based on whether I need one result or many."

What do different interview levels expect?

  • Junior: Create arrays, access indexes and use common methods.
  • Mid-level: Combine map, filter and reduce. Explain mutation clearly.
  • Senior: Discuss copying, performance, edge cases and readable data transformations.
  • Architect: Choose suitable data structures and explain application-level trade-offs.

15. Hands-On Practice

Try these exercises using the grocery shop theme first. Write the code before checking the hints.

Beginner

  1. Create an array with five grocery products. Print every product.
  2. Add one product using push().
  3. Remove the first product using shift().
  4. Find the index of "Milk" using indexOf().

Hint: Check the array after every operation.

Intermediate

  1. Find all products priced above 50 using filter().
  2. Create a new array containing only product names using map().
  3. Calculate the total price using reduce().
  4. Sort product prices from highest to lowest.

Hint: Store product details as objects with name and price properties.

Advanced

  1. Remove duplicate product names from an array.
  2. Group grocery products by category.
  3. Find the second-highest distinct product price.
  4. Build a shopping basket with add, remove and total operations.

Hint: Try Set, reduce(), filter() and sort(). Think about empty arrays and duplicate values.

16. Frequently Asked Questions

Can a JavaScript array store different data types?

Yes. An array can contain strings, numbers, booleans, objects and other arrays.

Can an array contain another array?

Yes. These are called nested arrays. Use flat() to flatten nested levels.

Does const make an array immutable?

No. const prevents reassignment of the variable. Array methods can still change its contents.

How do I remove duplicate values?

You can use Set to create an array with unique values.

Which array method should I use for totals?

Use reduce() when you need to combine values into one result.

Are arrays zero-indexed in JavaScript?

Yes. The first element uses index 0. The last index is length minus one.

17. Next Steps and Community

You now understand how JavaScript arrays store and process data. You have also explored common methods and their differences.

Try It Yourself

Build a grocery basket application. Add products, remove products and calculate the final total. Try each operation with different product lists.

Explore Further

Continue practising JavaScript functions, objects, loops and modern syntax. These topics work closely with arrays in real applications.

Share Your Knowledge

Share your solutions and discuss different approaches. Help other learners understand array operations through practical examples.

Key takeaway: Arrays help you manage related data in one place. Learn when to use each method, and always understand whether it changes the original array.

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.