# JavaScript Array Methods

 ### Introduction

If you are JavaScript developer and want to improve your coding, then you should be familiar with popular array methods to make our life easy to write code fast and make your code look clean and easy to understand.

So, in this blog we will learn some most popular JavaScript array methods. 

So, let's dive in.

## Array.forEach method

 **Syntax :**

```
arr.forEach(function callbackFunc(item, index, array) {
  // ... do something with item
});
``` 

> 
The `Array.forEach` method allows to run a function for every element of the array.

**Example :**


```
const languages = ['JavaScript','python','Java','c++'];

languages.forEach(function callbackFunc(language){
    console.log(language);
})

/* output :
  JavaScript 
  python
  Java
  c++ 
*/

``` 
The equivalent code for above using loop is :


```
const languages = ['JavaScript','python','Java','c++'];

for(let i = 0; i < languages.length; i++) {
  console.log(languages[i]);
}

/* output :
  JavaScript 
  python
  Java
  c++ 
*/
``` 
The most important thing you need to keep in mind that `forEach` method does not return any value.


```
const languages = ['JavaScript','python','Java','c++'];

const returnValue= languages.forEach(function callbackFunc(language){
    return language;
})

console.log("return value",returnValue); // undefined

/* output :
  JavaScript 
  python
  Java
  c++ 
*/
``` 

> Note that `forEach` method only used for loop through an array and perform some logging and processing. It does not return any value , even if you rerun value from callback function
(this means that `returnValue` comes as `undefined` in above example).

In above example we have used only one parameter of callback function. But, callback function also receives two parameters, which are :

- index - the index of the element which is currently iterated

- array - array which we are looping over i.e. 

```
const languages = ['JavaScript','python','Java','c++'];

``` 

```
const languages = ['JavaScript','python','Java','c++'];

languages.forEach(function callbackFunc(language,index, array){
    console.log(language, index, array);
})

/* output :
  JavaScript 0 ['JavaScript','python','Java','c++']
  python 1 ['JavaScript','python','Java','c++']
  Java 2 ['JavaScript','python','Java','c++']
  c++ 3 ['JavaScript','python','Java','c++'] */

``` 
Depending on the requirement you can use `index` and `array` parameters.

## Array.map method

The `Array.map` method is most popular method among all other array methods.

**Syntax :**

```
Array.map(function callbackFunc(currentvalue, index, array){
  // return element for new array
},[thisArg])

``` 
The `map` method executes callback function once for every element of the array and ** returns new array**.

**Example :**

```
const languages = ['JavaScript','python','Java','c++'];

const newArray = languages.map(function callbackFunc(language){
    return language.toUppercase();
})

console.log(newArray); //output : ["JAVASCRIPT","PYTHON","JAVA","C++"]

``` 
In the above code, we are converting each element to uppercase and returning it.


> Note that, `map` method returns new array with exact same length as original array.

The difference between `forEach` and `map` is that `forEach` is only used for looping and does not returned anything back. On the other hand, `map` is returns new array with exact same length as that of original array.  

Also note that, `map` does not change original array but returns new array.

## Array.filter method

**Syntax :**

```
Array.filter(function callbackFunc(currentvalue, index, array){
  // return element for new array
},[thisArg])

``` 

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

**Example :**

```
const languages = ['JavaScript','python','Java','c++'];

const result = languages.filter(language => language.length > 4);

console.log(result); //['JavaScript','python'];

``` 
As seen in above code `filter` method helps to find all elements from the array that match the specified test condition.


> The main difference between `find` and `filter` is that `find` only returns the first matching element of the array, but using `filter` returns all the matching elements from the array.

Note that, If no element passes to the test condition, an empty array will be returned.


## Array.reduce method

**Syntax :**

```
reduce(function callbackFn(accumulator, currentValue, index, array) { ... }, initialValue)

``` 
The `reduce()` method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.


> Note that, output of `reduce` method is always be single value. It can be object, a string, a number, an array and so on. But, `reduce` method always reduce single value as output.

**Example :**

```
const numbers= [1,2,3,4];

const sum = numbers.reduce(function (accumulator, number){
 return accumulator + number;
}, 0);

console.log(sum);  //10
``` 
The `reduce` method accepts callback function that receives `accumulator`,`number`,`index`,`array` as parameters. But, in above code we are only using `accumulator` and `number` parameters.

The `accumulator` contains `initialValue` to be used by array. `initialValue` decides the type of data returned by the `reduce` method.

The `number` is the second parameter in the callback function which takes array element during each iteration of loop.

In the above code, we have provided 0 as `initialValue` for the `accumulator`. In the first time callback function executes `accumulator + number` will be `0 + 1 = 1` and we are returning the value back to value `1`.

So, for further callback function execution the reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and becomes the final, single resulting value.

In the above code `initialValue` is `0` is not required because all the elements in the array are integers.

So, below code is also work :

```
const numbers= [1,2,3,4];

const sum = numbers.reduce(function (accumulator, number){
 return accumulator + number;
});

console.log(sum);  //10
``` 
Here, `accumulator` contain first element of the array and `number` will contain the next element of the array (in the first iteration `1 + 2 = 3` and `3 + 3 = 6` in next iteration and so on).

### Thanks for Reading!

References : 

-  [MDN Doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods) 

-  [JavaScript info](https://javascript.info/array-methods) 

















