JavaScript provides a wide range of built-in methods that you can use to manipulate and work with arrays. These methods allow you to perform various operations such as adding, removing, modifying, and searching for elements in an array. Here are some commonly used array methods in JavaScript:
push(): Adds one or more elements to the end of an array and returns the new length of the array.
var fruits = ["apple", "banana"];
fruits.push("orange", "mango");
console.log(fruits); // Output: ["apple", "banana", "orange", "mango"]
pop(): Removes the last element from an array and returns that element.
var fruits = ["apple", "banana", "orange"];
var lastFruit = fruits.pop();
console.log(lastFruit); // Output: "orange"
console.log(fruits); // Output: ["apple", "banana"]
concat(): Combines two or more arrays and returns a new array.
var fruits = ["apple", "banana"];
var moreFruits = ["orange", "mango"];
var allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ["apple", "banana", "orange", "mango"]
join(): Joins all elements of an array into a string, using a specified separator.
var fruits = ["apple", "banana", "orange"];
var fruitString = fruits.join(", ");
console.log(fruitString); // Output: "apple, banana, orange"
reverse(): Reverses the order of the elements in an array.
var fruits = ["apple", "banana", "orange"];
fruits.reverse();
console.log(fruits); // Output: ["orange", "banana", "apple"]
sort(): Sorts the elements of an array in place, either alphabetically or based on a custom sort order.
var fruits = ["banana", "apple", "orange"];
fruits.sort();
console.log(fruits); // Output: ["apple", "banana", "orange"]
slice(): Returns a shallow copy of a portion of an array into a new array, selected from a start index to an end index.
var fruits = ["apple", "banana", "orange", "mango", "kiwi"];
var slicedFruits = fruits.slice(1, 4);
console.log(slicedFruits); // Output: ["banana", "orange", "mango"]
indexOf(): Returns the index of the first occurrence of a specified element in an array, or -1 if the element is not found.
var fruits = ["apple", "banana", "orange"];
var bananaIndex = fruits.indexOf("banana");
console.log(bananaIndex); // Output: 1
forEach(): Executes a provided function once for each element in an array.
var fruits = ["apple", "banana", "orange"];
fruits.forEach(function (fruit) {
console.log(fruit);
});
// Output:
// "apple"
// "banana"
// "orange"
These are just a few examples of the array methods available in JavaScript. There are many more methods you can explore, such as splice(), filter(), map(), reduce(), and more. These methods provide powerful ways to manipulate and work with arrays in JavaScript.