# Js Array Common Method 2

### 1. forEach

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

{% tabs %}
{% tab title="JavaScript" %}
```javascript
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"
```
{% endtab %}
{% endtabs %}

### 2. map

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

{% hint style="danger" %}
The **`map()`** method **creates a new array**
{% endhint %}

{% tabs %}
{% tab title="JavaScript" %}
```javascript
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
```
{% endtab %}
{% endtabs %}

### 3. every and some

The **`every()`** method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.\
The **`some()`** method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.\


### 4. reduce /reduceRight

The **`reduce()`** method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

Perhaps the easiest-to-understand case for `reduce()` is to return the sum of all the elements in an array.

The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.

{% tabs %}
{% tab title="JavaScript" %}
```javascript
const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
```
{% endtab %}
{% endtabs %}

### 5. indexOf / lastIndexOf

The **`indexOf()`** method returns the first index at which a given element can be found in the array, or -1 if it is not present.

{% tabs %}
{% tab title="JavaScript" %}
```javascript
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
```
{% endtab %}
{% endtabs %}
