Common Array Methods in JavaScript

JavaScript arrays come with many built-in methods that allow you to manipulate, access, and modify the array elements efficiently. Below are some common array methods:

1. forEach()

The forEach() method executes a provided function once for each array element.


const numbers = [1, 2, 3, 4];
numbers.forEach(num => console.log(num * 2)); 
    

Output: 2 4 6 8

2. map()

The map() method creates a new array with the results of calling a provided function on every element in the array.


const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
    

Output: [2, 4, 6, 8]

3. filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.


const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
    

Output: [2, 4]

4. reduce()

The reduce() method applies a function to reduce the array to a single value (e.g., sum, product, etc.).


const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);
    

Output: 10

5. find()

The find() method returns the first element that satisfies the provided testing function.


const numbers = [1, 2, 3, 4, 5];
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven);
    

Output: 2

6. some()

The some() method tests whether at least one element in the array passes the provided function.


const numbers = [1, 2, 3, 4];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven);
    

Output: true

7. every()

The every() method tests whether all elements in the array pass the provided function.


const numbers = [2, 4, 6, 8];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven);
    

Output: true

8. sort()

The sort() method sorts the elements of an array in place and returns the sorted array.


const numbers = [4, 1, 3, 2];
numbers.sort((a, b) => a - b);
console.log(numbers);
    

Output: [1, 2, 3, 4]

Conclusion

These are just a few of the many array methods in JavaScript. They allow for easy manipulation of arrays, making JavaScript programming more efficient and intuitive.