The Wayback Machine - https://web.archive.org/web/20240828192647/https://www.geeksforgeeks.org/javascript-array-methods/
Open In App

JavaScript Array Methods

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript array methods are built-in functions that allow efficient manipulation and traversal of arrays. They provide essential functionalities like adding, removing, and transforming elements, as well as searching, sorting, and iterating through array elements, enhancing code readability and productivity.

Learn More on JavaScript Array

Now let’s look at the JS array methods and properties.

JavaScript Array Methods

Below is the JavaScript Array Methods list, covering all important array methods and properties in JavaScript with examples.

Let’s discuss these JavaScript array methods and examples, to understand their functioning and uses.

JavaScript Array length 

The length property returns the length of the given array.

Syntax:

Array.length

Example: Getting the length of the given array.

JavaScript
// Original Array
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing the Array Length
console.log(courses.length);

Output
4

JavaScript Array toString() Method

The toString() method converts the given value into the string.

Syntax:

arr.toString()

Example: Converting the given array into the strings.

JavaScript
// Original Array
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Converting array ot String
let str = courses.toString();

console.log(str);

Output
HTML,CSS,JavaScript,React

JavaScript Array join() Method

This join() method creates and returns a new string by concatenating all elements of an array. It uses a specified separator between each element in the resulting string.

Syntax

array.join(separator)

Example: Joining the given array by the “|” symbol.

JavaScript
// Original Array
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Joining the array elements
console.log(courses.join('|'));

Output
HTML|CSS|JavaScript|React

JavaScript Array delete Operator

The delete operator is used to delete the given value which can be an object, array, or anything.

Syntax:

delete object
// or
delete object.property
// or
delete object['property']

Example: Deleting the given object’s property by using the delete operator.

JavaScript
let emp = { 
    firstName: "Raj", 
    lastName: "Kumar", 
    salary: 40000 
} 

console.log(delete emp.salary); 
console.log(emp);

Output
true
{ firstName: 'Raj', lastName: 'Kumar' }

JavaScript Array concat() Method

The concat() method is used to concatenate two or more arrays and it gives the merged array.

Syntax:

let newArray = arr.concat()  // or
let newArray = arr1.concat(arr2) // or
let newArray = arr1.concat(arr2, arr3, ...) // or
let newArray = arr1.concat(value0, value1)

Example: Concatenate method to concatenate of three arrays.

JavaScript
// Declare three arrays
let arr1 = [11, 12, 13];
let arr2 = [14, 15, 16];
let arr3 = [17, 18, 19];

let newArr = arr1.concat(arr2, arr3);
console.log(newArr);

Output
[
  11, 12, 13, 14, 15,
  16, 17, 18, 19
]

JavaScript Array flat() Method

The flat() method is used to flatten the array i.e. it merges all the given array and reduces all the nesting present in it.

Syntax:

arr.flat([depth])

Example: Reducing the nesting of the given array using the flat() method.

JavaScript
// Creating multilevel array
const arr = [['1', '2'], ['3', '4', '5',['6'], '7']];

// Flat the multilevel array
const flatArr= arr.flat(Infinity);
console.log(flatArr);

Output
[
  '1', '2', '3',
  '4', '5', '6',
  '7'
]

Javascript Array.push() Method

The push() method is used to add an element at the end of an Array. As arrays in JavaScript are mutable objects, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array. 

Syntax:

Array.push(item1, item2 …)

Example : Adding new elements such as some numbers and some string values to the end of the array using the push() method.

JavaScript
// Declaring and initializing arrays
let numArr = [10, 20, 30, 40, 50];

// Adding elements at the end of an array
numArr.push(60);
numArr.push(70, 80, 90);
console.log(numArr);


let strArr = ["piyush", "gourav", "smruti", "ritu"];
strArr.push("sumit", "amit");

console.log(strArr);

Output
[
  10, 20, 30, 40, 50,
  60, 70, 80, 90
]
[ 'piyush', 'gourav', 'smruti', 'ritu', 'sumit', 'amit' ]

Javascript Array.unshift() Method

The unshift() method is used to add elements to the front of an Array.

Syntax:

Array.unshift(item1, item2 …)

Example : Adding new elements to the beginning of the array using the unshift() method.

JavaScript
// Declaring and initializing arrays
let numArr = [20, 30, 40];

// Adding element at the beginning
// of an array
numArr.unshift(10, 20);
console.log(numArr);


// Declaring and initializing arrays
let strArr = ["amit", "sumit"];

// Adding element at the beginning
// of an array
strArr.unshift("sunil", "anil");
console.log(strArr);

Output
[ 10, 20, 20, 30, 40 ]
[ 'sunil', 'anil', 'amit', 'sumit' ]

JavaScript Array.pop() Method

The pop() method is used to remove elements from the end of an array. 

Syntax:

Array.pop()

Example: Remove an element from the end of the array using the pop() method.

JavaScript
// Declare and initialize array
let numArr = [20, 30, 40, 50];

// Removing elements from end 
// of an array
numArr.pop();

console.log(numArr);


// Declare and initialize array
let strArr = ["amit", "sumit", "anil"];

// Removing elements from end 
// of an array
strArr.pop();

console.log(strArr);

Output
[ 20, 30, 40 ]
[ 'amit', 'sumit' ]

JavaScript Array.shift() Method

The shift() method is used to remove elements from the beginning of an array 

Syntax:

Array.shift()

Example: Remove an element from the beginning of an array.

JavaScript
// Declare and initialize array
let numArr = [20, 30, 40, 50];

// Removing elements from the 
// beginning of an array
numArr.shift();

console.log(numArr);


// Declare and initialize array
let strArr = ["amit", "sumit", "anil"];

// Removing elements from the 
// beginning of an array
strArr.shift();

console.log(strArr);

Output
[ 30, 40, 50 ]
[ 'sumit', 'anil' ]

JavaScript Array.splice() Method

The splice() method is used to Insert and Remove elements in between the Array.

Syntax:

Array.splice (start, deleteCount, item 1, item 2….) 

Example: Removing an element and adding new elements at the same time using the splice() method.

JavaScript
// Declare and initialize array
let numArr = [20, 30, 40, 50];

// Removing an adding element at a 
// particular location in an array

// Delete 3 elements starting from index 1
numArr.splice(1, 3);

// Insert 80, 90, 100 at starting index 1
numArr.splice(1, 0, 3, 4, 5);

console.log(numArr);


// Declare and initialize array
let strArr = ["amit", "sumit", "anil"];

// Delete two elements starting from index 1
// and add three elements.
strArr.splice(1, 2, "Geeks", "Geeks1", "Geeks2");

Output
[ 20, 3, 4, 5 ]

JavaScript Array.slice() Method

The slice() method returns a new array containing a portion of the original array, based on the start and end index provided as arguments

Syntax:

Array.slice (startIndex , endIndex);

Example: Cover all slice() method corner cases.

JavaScript
// Original Array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Case 1: Extract the first 3 elements of the array
const case1 = arr.slice(0, 3);
console.log("First 3 Array Elements: ", case1);

// Case 2: Extract the last 3 array elements
const case2 = arr.slice(-3);
console.log("Last 3 Array Elements: ", case2);

// Case 3: Extract elements from middle of array
const case3 = arr.slice(3, 7);
console.log("Case 3: Extract elements from middle: ", case3);

// Case 4: Start index is greater than end index
const case4 = arr.slice(5, 2);
console.log("Case 4: Start index is greater than end index: ", case4);

// Case 5: Negative start index
const case5 = arr.slice(-4, 9);
console.log("Case 5: Negative start index: ", case5);

// Case 6: Negative end index
const case6 = arr.slice(3, -2);
console.log("Case 6: Negative end index: ", case6);

// Case 7: Only start index is provided
const case7 = arr.slice(5);
console.log("Case 7: Only start index is provided: ", case7);

// Case 8: Start index and end index are out of range
const case8 = arr.slice(15, 20);
console.log("Case 8: Start and end index out of range: ", case8);

// Case 9: Start and end index are negative
// and out of range
const case9 = arr.slice(-15, -10);
console.log("Case 9: Start and end index are negative"
    + " and out of range: ", case9);

Output
First 3 Array Elements:  [ 1, 2, 3 ]
Last 3 Array Elements:  [ 8, 9, 10 ]
Case 3: Extract elements from middle:  [ 4, 5, 6, 7 ]
Case 4: Start index is greater than end index:  []
Case 5: Negative star...

JavaScript Array some() Method

The some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument function.

Syntax:

array.some(callback(element, index, array), thisArg);

Example: Basic example of Array some() method.

JavaScript
function isGreaterThan5(element, index, array) {
    return element > 5;
}


// Driver code
// Original array
let array = [2, 5, 8, 1, 4];

// Checking for condition in array
let value = array.some(isGreaterThan5);

console.log(value);

Output
true

JavaScript Array reduce() Method

The reduce() method is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.

Syntax:

array.reduce(callback(accumulator, currentValue, index, array), initialValue);

Example: Here is an example of the basic use of the Array reduce() method.

JavaScript
// Original array
let arr = [88, 50, 25, 10];

// Perform reduce method
let sub = arr.reduce(geeks);

function geeks(total, num) {
    return total - num;
}

console.log(sub);

Output
3

JavaScript Array map() Method

The map() method creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. This method iterates over an array and calls the function on every element of an array.

Syntax:

array.map(callback(currentValue, index, array), thisArg);

Example: Here is an example of the basic use of the Array map() method.

JavaScript
// Original array
let arr = [4, 9, 16, 25];

// Performing map method
let sub = arr.map(geeks);

function geeks() {
    return arr.map(Math.sqrt);
}

console.log(sub);

Output
[ [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ] ]

Javascript Array reverse() method

The reverse() method is used to reverse the order of elements in an array. It modifies the array in place and returns a reference to the same array with the reversed order.

Syntax:

array.reverse()

Example: Here is an example shows the use of the Array reverse() method.

JavaScript
let array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array);

Output
[ 5, 4, 3, 2, 1 ]

Javascript Array values() method

The values() method returns a new Array Iterator object that contains the values for each index in the array.

Syntax:

Array.values()

Example: Here is an example shows the use of the Array values() method.

JavaScript
const fruits = ["Apple", "Banana", "Cherry"];

// Get the iterator object
const iterator = fruits.values();

// Iterate over the values using the iterator
for (const value of iterator) {
  console.log(value);
}

Output
Apple
Banana
Cherry

JavaScript Array Complete Reference

We have created a complete list of array methods, please check this article JavaScript Array Complete Reference for more details.

Note: All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console. 

Learn JavaScript from beginners to advanced with JavaScript Tutorial



Previous Article
Next Article

Similar Reads

JavaScript Array Iteration Methods
JavaScript Array iteration methods perform some operation on each element of an array. Array iteration means accessing each element of an array. There are some examples of Array iteration methods are given below: Using Array forEach() MethodUsing Array some() MethodUsing Array map() MethodMethod 1: Using Array forEach() MethodThe array.forEach() me
3 min read
Chaining of Array Methods in JavaScript
There are some methods in JavaScript that can loop through the array. We already have a knowledge about these array methods. Filter method ( filter()) Map method ( map()) Reduce method ( reduce()) Find method ( find()) Sort method ( sort()) We will learn how to chain all the array methods together. Example: const products = [ // Here we create an o
3 min read
Some newly introduced array methods in JavaScript ES6
An array is used to store the elements of multiple data types in JavaScript altogether. Also, there are certain times when you have to manipulate the response received from the APIs as per the requirements on the webpages. Sometimes, the responses are objects and have to be converted to the arrays to perform the desired operations. These methods of
3 min read
How to define custom Array methods in JavaScript?
JavaScript arrays are versatile data structures used to store collections of items. When you want to iterate through the elements of an array, it's common to use loops like for, for...of, or forEach. However, there's a nuance when it comes to iterating through arrays that have additional properties added through their prototype. In this article, we
2 min read
What are the Important Array Methods of JavaScript ?
In this article, we will try to understand various important Array methods (like push(), pop(), and so on) with the help of certain examples. Let us first understand how we can create an array in JavaScript by using certain syntax provided. Syntax: let array = [element1, element2, .....]Alternatively, we may also use the Array class (using a new ke
7 min read
Best-Known JavaScript Array Methods
An array is a special variable in all programming languages used to store multiple elements. JavaScript array come with built-in methods that every developer should know how to use. These methods help in adding, removing, iterating, or manipulating data as per requirements. There are some Basic JavaScript array methods which are as follows: Table o
7 min read
JavaScript ES5 Object Methods
The ES5 Object method in javascript is used to find more methods to interact with the objects. The ES5 Object method can do: prevents enumeration manipulation deletion prevent addition of new features getters and setters Syntax: Object.defineProperty(object, property, {value : value}) The following Meta Data value can be true or false: writable enu
2 min read
How to compare isNaN() and isInteger() Methods in JavaScript ?
JavaScript provides various in-built functions that developers can use to check the type of values of variables. Two such functions are isNaN() and isInteger(). In this article, we will discuss the difference between these two functions and when to use them. isNaN() Method: The JavaScript isNaN() method is used to check whether a given value is an
2 min read
JavaScript Set Date Methods
There are various methods to set the date in JavaScript. The data values can be set like years, months, days, hours, minutes, seconds, and milliseconds for a Date Object. Method: setDate(): It is used to set the day as a number (1-31).setFullYear(): It is used to set the year (optionally month and day).setHours(): It is used to set the hour (0-23).
2 min read
JavaScript Object Methods
Object Methods in JavaScript can be accessed by using functions. Functions in JavaScript are stored as property values. The objects can also be called without using brackets (). In a method, 'this' refers to the owner object.Additional information can also be added along with the object method.Syntax: objectName.methodName()Properties: A function m
2 min read
JavaScript Methods to Increment/Decrement Alphabetical Letters
The task is to increment/decrement alphabetic letters using ASCII values with the help of JavaScript. Approach: Use charCodeAt() method to return the Unicode of the character at the specified index in a string.Increment/Decrement the ASCII value depending on the requirement.Use fromCharCode() method to convert Unicode values into characters. Exampl
2 min read
What is the difference between find() and filter() methods in JavaScript ?
In this article, we will see the difference between the find() and filter() methods in javascript. JavaScript find() method: The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to the leaf. Syntax: array.find(function(currentValue, index, arr),thi
2 min read
JavaScript Helper Methods
An array in JavaScript is usually considered a "list-objects". In simple words, we can say an array is an object that contains some values. But an array is a special object in JavaScript. An array can store heterogeneous data structures. It can store data values of any type like objects and array. Example: In this example, a Javascript array is cre
15+ min read
JavaScript Reflect Methods
Reflect is a built-in JavaScript object which gives access to other methods for interceptable operations. JavaScript Reflect methods are the same as those of proxy handlers and are static just like the Math object. As it is not a JavaScript function object, so it's not constructible. It cannot be used with the JavaScript new operator and cannot be
3 min read
JavaScript Intl Methods
Intl Method: The Intl() method is used to format strings, numbers, dates, and times in local format with the help of constructors. Syntax: new Intl.constructors(locales, options); Parameters: locales argument: locales argument is used to determine the locale used in operation. locales may be :undefined: default locales are used.A locale: A locale i
5 min read
Difference between preventDefault() and stopPropagation() methods in JavaScript
In this article, we will be discussing the PreventDefault & stopPropagation methods with suitable code examples for each condition & then we will see the difference between the PreventDefault vs stopPropagation. JavaScript preventDefault() Method: It is a method present in the event interface. This method prevents the browser from executing
3 min read
What is the drawback of creating true private methods in JavaScript ?
According to other programming languages like c++, java, etc. private is something that can't be shared with other classes, which cannot be accessed directly using objects. The same rule applies to JavaScript also. So first we have to look at how private methods are made using JavaScript? There are mainly four keywords using that we can make a priv
3 min read
Explain call() and apply() methods in JavaScript
Call() Method: The call method is basically used to invoke the function with different this object. In JavaScript, this refers to an object. It depends on how we are calling a particular function. In the global scope, this refers to the global object window. Inside function also this refers to the global object window. In strict mode, when we use a
3 min read
Difference between Set.clear() and Set.delete() Methods in JavaScript
Both Set.clear() and Set.delete() methods modify the present Set by removing elements. But there are some fundamental differences between these two, which will be discussed in this article. Set.clear() Method: In this method, all the elements in the set get deleted. So, as a result, the set becomes empty and the size of the set becomes 0. Syntax: M
2 min read
Tips and Tricks on JavaScript DOM Methods
DOM stands for Document Object Model. It is a programming interface for web documents that represents the page so that programs can change the document structure, style, and content. In simpler terms, the DOM is a tree-like structure that represents the HTML content of a web page in a structured manner, allowing JavaScript to manipulate the content
9 min read
How to Change CSS Properties using JavaScript EventListner Methods ?
In this article, we will be using JavaScript to update the web page's CSS styling by taking input from the user. Generally, we have seen a few webpages update the various styling properties dynamically by taking the user input that enhances the user interaction with the webpage, along with improving the overall user experience by engaging the users
3 min read
What is the difference between every() and some() methods in JavaScript ?
In this article, we will see the difference between every() and some() methods in JavaScript. Array.every() methodThe Array.every() method in JavaScript is used to check whether all the elements of the array satisfy the given condition or not. The output will be false if even one value does not satisfy the element, else it will return true, and it
3 min read
JavaScript Get Date Methods
JavaScript Date Object allows us to get and set the date values. In this article, we will know how to get the various date methods from the date object in Javascript. There are various methods that retrieve the date in JavaScript. The date values can get like years, months, days, hours, minutes, seconds, and milliseconds from a Date Object. The fol
3 min read
Difference Between Promise.resolve() & Promise.reject() methods in JavaScript
Promise.resolve() and Promise.reject() are both methods provided by the Promise object in JavaScript. They serve different purposes in handling asynchronous operations: Promise.resolve():Creates a new Promise object that is resolved with the provided value or a resolved Promise object if the provided value is already a Promise.Example:const resolve
1 min read
How to use every() or some() methods in JavaScript ?
In JavaScript, the every() and some() methods are array methods used to check the elements of an array based on a given condition. every(): Checks if all elements in an array satisfy a condition.some(): Checks if at least one element in an array satisfies a condition.Table of Content every() Methodsome() Methodevery() MethodThe every() method tests
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
JavaScript String Methods
JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. JavaScript provides a bunch of string methods for representing and manipulating strings. From retrieving specific cha
15 min read
Static Methods in JavaScript
JavaScript Static methods are defined directly on the classes, not on the instances of the class. Static methods can be of any name. A class can contain more than one static method. Note: "this" keyword is used to call a static method within any other static method in JavaScript. Example 1: The following is the code to invoke one static method. [GF
2 min read
Difference between Object.keys() and Object.entries() methods in JavaScript
Object.keys() and Object.entries() are methods in JavaScript used to iterate over the properties of an object. They differ in how they provide access to object properties: Object.keys() returns an array of a given object's own enumerable property names, while Object.entries() returns an array of a given object's own enumerable string-keyed property
2 min read
Difference between Methods and Functions in JavaScript
Grasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and functions in JavaScript, explaining their unique charac
3 min read