JavaScript Array Methods: Create with Example

⚡ Smart Summary

JavaScript Array Methods allow developers to store, retrieve, and transform ordered collections of values through a single object. This article explains array creation, index access, the built-in method families, iteration techniques, multidimensional structures, and a runnable example with expected output.

  • 📦 Core Concept: An array is an object that holds many values under one name and exposes each value through a zero-based index.
  • 🛠️ Creation Syntax: Literal notation with square brackets is preferred, while the Array constructor remains available for legacy code.
  • Mutating Methods: push, pop, shift, unshift, and splice change the original array and return either the removed value or the new length.
  • 🔍 Non-Mutating Methods: slice, concat, join, indexOf, and includes read the array without altering the stored elements.
  • 🔁 Iteration Family: forEach, map, filter, reduce, and find apply a callback to every element and support functional programming patterns.
  • ⚠️ Sorting Caution: The default sort compares values as strings, so numeric data requires an explicit comparator function.
  • 🧱 Nested Structures: Placing arrays inside arrays produces a multidimensional grid addressed with two index expressions.

JavaScript Array Methods

What is an Array in JavaScript?

An array is an object that can store a collection of items. Arrays become really useful when you need to store large amounts of data of the same type. Suppose you want to store details of 500 employees. If you are using variables, you will have to create 500 variables, whereas you can do the same with a single array. You can access the items in an array by referring to its index number, and the index of the first element of an array is zero.

Unlike arrays in strictly typed languages, a JavaScript array is dynamic. Its length grows automatically when a new element is assigned, and a single array may hold strings, numbers, booleans, objects, and even other arrays at the same time. This flexibility makes arrays the default container for list data in browser scripts and server-side code alike.

How to Create an Array in JavaScript

You can create an array in JavaScript as given below.

var students = ["John", "Ann", "Kevin"];

Here, you are initializing your array as and when it is created with values “John”, “Ann” and “Kevin”. The index of “John”, “Ann” and “Kevin” is 0, 1 and 2 respectively. If you want to add more elements to the students array, you can do it like this:

students[3] = "Emma";
students[4] = "Rose";

You can also create an array using the Array constructor like this:

var students = new Array("John", "Ann", "Kevin");

OR

var students = new Array();

students[0] = "John";

students[1] = "Ann";

students[2] = "Kevin";

How to Access and Modify Array Elements

Every element sits at a numbered position. Square bracket notation reads a value, assigns a new value, or appends a fresh entry when the index equals the current length.

let students = ["John", "Ann", "Kevin"];

console.log(students[0]);              // John  - first element
console.log(students[students.length - 1]); // Kevin - last element

students[1] = "Anna";                // replace an existing value
students[3] = "Emma";                // append a new value

console.log(students);              // ["John", "Anna", "Kevin", "Emma"]
console.log(students.length);       // 4
console.log(students[9]);              // undefined - index does not exist

⚠️ Warning: Assigning a value to an index far beyond the current length creates a sparse array filled with empty slots. Use push() instead of a jumped index so the array stays dense and predictable.

JavaScript Array Methods

The Array object has many properties and methods which help developers to handle arrays easily and efficiently. You can get the value of a property by specifying arrayname.property and the output of a method by specifying arrayname.method().

  1. length property –> If you want to know the number of elements in an array, you can use the length property.
  2. prototype property –> If you want to add new properties and methods, you can use the prototype property.
  3. reverse method –> You can reverse the order of items in an array using a reverse method.
  4. sort method –> You can sort the items in an array using the sort method.
  5. pop method –> You can remove the last item of an array using a pop method.
  6. shift method –> You can remove the first item of an array using the shift method.
  7. push method –> You can add a value as the last item of the array.

The reference table below groups the most frequently used methods so you can see at a glance which ones change the original array and which ones return a new value.

Method Purpose Returns Changes Original Array
push() Add one or more items to the end New length Yes
pop() Remove the last item Removed item Yes
unshift() Add one or more items to the front New length Yes
shift() Remove the first item Removed item Yes
splice() Insert or delete items at any position Array of removed items Yes
sort() Order the items The sorted array Yes
reverse() Invert the order of items The reversed array Yes
slice() Copy a section of the array New array No
concat() Join two or more arrays New array No
join() Combine items into a string String No
indexOf() Find the position of a value Index or -1 No
includes() Test whether a value exists true or false No

Adding and Removing Elements

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

fruits.push("cherry");      // ["apple", "banana", "cherry"]
fruits.unshift("mango");    // ["mango", "apple", "banana", "cherry"]
fruits.pop();                // ["mango", "apple", "banana"]
fruits.shift();              // ["apple", "banana"]

// splice(startIndex, deleteCount, ...itemsToInsert)
fruits.splice(1, 0, "kiwi"); // ["apple", "kiwi", "banana"]
console.log(fruits);

Searching, Copying, and Joining

let colors = ["red", "green", "blue", "green"];

console.log(colors.indexOf("green"));     // 1  - first match only
console.log(colors.lastIndexOf("green")); // 3
console.log(colors.includes("pink"));     // false
console.log(colors.slice(1, 3));         // ["green", "blue"]
console.log(colors.join(" | "));         // red | green | blue | green
console.log(colors.concat(["black"]));   // new array, colors unchanged

Iteration Methods: forEach, map, filter, and reduce

Modern JavaScript favours callback-driven methods over manual index loops, because the intent of the operation is stated directly in the method name.

const scores = [45, 72, 88, 31, 95];

scores.forEach(s => console.log(s));   // prints each score

const doubled = scores.map(s => s * 2);  // [90, 144, 176, 62, 190]
const passed  = scores.filter(s => s >= 50); // [72, 88, 95]
const total   = scores.reduce((sum, s) => sum + s, 0); // 331
const first   = scores.find(s => s > 80);   // 88

console.log(doubled, passed, total, first);

💡 Tip: The default sort() converts elements to strings, so [10, 9, 100].sort() returns [10, 100, 9]. Pass a comparator such as sort((a, b) => a - b) to sort numbers correctly.

JavaScript Array Example with Source Code

The script below builds a students array, adds a custom display method through the prototype property, and then demonstrates length, sort, reverse, pop, and push in sequence. Try this yourself:

<html>
<head>
	<title>Arrays!!!</title>
	<script type="text/javascript">
		var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
		Array.prototype.displayItems=function(){
			for (i=0;i<this.length;i++){
				document.write(this[i] + "<br />");
			}
		}
		document.write("students array<br />");
		students.displayItems();
		document.write("<br />The number of items in students array is " + students.length + "<br />");
		document.write("<br />The SORTED students array<br />");
		students.sort();
		students.displayItems();
		document.write("<br />The REVERSED students array<br />");
		students.reverse();
		students.displayItems();
		document.write("<br />THE students array after REMOVING the LAST item<br />");
		students.pop();
		students.displayItems();
        document.write("<br />THE students array after PUSH<br />");
        students.push("New Stuff");
		students.displayItems();
	</script>
</head>
<body>
</body>
</html>

Expected Output:

students array
John
Ann
Aaron
Edwin
Elizabeth

The number of items in students array is 5

The SORTED students array
Aaron
Ann
Edwin
Elizabeth
John

The REVERSED students array
John
Elizabeth
Edwin
Ann
Aaron

THE students array after REMOVING the LAST item
John
Elizabeth
Edwin
Ann

THE students array after PUSH
John
Elizabeth
Edwin
Ann
New Stuff

Notice that sort places “Aaron” before “Ann” because uppercase and lowercase letters are compared by their character codes. Notice also that pop removed “Aaron” from the reversed array, which confirms that both sort and reverse changed the original array in place.

How to Loop Through a JavaScript Array

Four looping styles are available, and each one suits a different situation. The classic for loop gives full control over the index, for…of reads values directly, forEach expresses intent clearly, and for…in should be reserved for object properties.

const cities = ["Paris", "Tokyo", "Cairo"];

// 1. Classic for loop - index is available
for (let i = 0; i < cities.length; i++) {
    console.log(i + ": " + cities[i]);
}

// 2. for...of loop - value is available
for (const city of cities) {
    console.log(city);
}

// 3. forEach with index parameter
cities.forEach((city, index) => console.log(index, city));

// 4. entries() when both index and value are needed
for (const [index, city] of cities.entries()) {
    console.log(index, city);
}

A deeper treatment of loop syntax, including while and do…while, appears in the article on how to use loops in JavaScript.

Multidimensional Arrays in JavaScript

JavaScript has no dedicated matrix type. A grid is simply an array whose elements are themselves arrays, and two index expressions are used to reach a single cell.

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

console.log(matrix[1][2]); // 6  - row index 1, column index 2

for (const row of matrix) {
    console.log(row.join(" "));
}

// flatten a nested array into a single level
console.log(matrix.flat()); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

6
1 2 3
4 5 6
7 8 9
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Arrays appear in almost every practical script, from form validation to data rendering. Continue with the practical JavaScript code examples, review JavaScript strings for text handling, and read about internal and external JavaScript to decide where these scripts belong in a page. Developers who want static type checking over array contents can move on to the TypeScript tutorial.

FAQs

An array stores an ordered list addressed by numeric indexes, while an object stores named properties in no guaranteed order. Arrays inherit list methods such as push and map that plain objects do not provide.

Use Array.isArray(value), which returns true only for arrays. The typeof operator is unreliable here because it reports “object” for arrays, dates, and null alike.

Use the spread syntax […original] or original.slice(). Plain assignment copies only the reference, so edits through either variable would affect the same underlying array.

Find the position with indexOf and pass it to splice, for example arr.splice(arr.indexOf(“Ann”), 1). Alternatively, filter returns a new array that excludes the unwanted value.

Arrays hold chat message histories, embedding vectors, and streamed model tokens in the browser. Methods such as map and reduce reshape those collections before they are sent to an API or rendered.

Yes, and they usually do. Still confirm whether the suggested method mutates the original array, because an unexpected splice or sort can corrupt state in a React or Vue component.

Summarize this post with: