JavaScript provides several built-in methods for working with arrays. Here are some commonly used array methods:
- push(): Adds one or more elements to the end of an array and returns the new length of the array.
const fruits = ['apple', 'banana'];
fruits.push('orange', 'grape');
console.log(fruits);
// fruits is now ['apple', 'banana', 'orange', 'grape']
- pop(): Removes the last element from an array and returns that element.
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(fruits)
// removedFruit is 'orange', fruits is now ['apple', 'banana']
- shift(): Removes the first element from an array and returns that element.
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
// removedFruit is 'apple', fruits is now ['banana', 'orange']
console.log(fruits);
- unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(fruits);
// removedFruit is 'apple', fruits is now ['banana', 'orange']
- indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.
const fruits = ['apple', 'banana', 'orange'];
const index = fruits.indexOf('banana');
console.log(index);
// index is 1
- splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'grape', 'kiwi');
console.log(fruits);
// fruits is now ['apple', 'grape', 'kiwi', 'orange']
- slice(): Returns a shallow copy of a portion of an array into a new array.
const fruits = ['apple', 'banana', 'orange', 'grape'];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits);
// slicedFruits is ['banana', 'orange'], fruits remains unchanged
- forEach(): Executes a provided function once for each array element.
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit) => {
console.log(fruit);
});
console.log(fruits);
// Outputs: apple, banana, orange
These are just a few examples, and JavaScript provides many more array methods for various operations. Understanding these methods can make it easier to work with arrays in JavaScript.
Top comments (0)