# Array Methods You Must Know

## push() and pop()

### Push()

Push is used to add an element or insert an element in the existing array at the end of that and return the lenght of that array.

It is a mutable method. What is the meaning of mutable ? It means the operation what are performing on that array that will reflect in the original array.

let's understand with some example:

```javascript
const array = [1,2,3,4,5]
console.log(array.push(6))  // 6 it is not element of that array it is the lenght of that array
// this will print the length of the array after the adding the element at the end 
console.log(array) // this will print the elements of that array
```

Now you might thinking that it is only for the array type object but that is not it you want to push an element to an object then also you can push values not the key.  
Now the question is if we can't pass the key value throught the push method then what will be the key for that? And this is the main thing in this part of the push method.

Let's understand this through an example

```javascript
const data = {
    "0": 1,
    "1": 2
};
Array.prototype.push.call(data,1,2); 
console.log(data) // {0: 1, 1: 2, a: 1, b: 2, length: 2}
```

If in case you don't know about the call method then [mdn call method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) you can refer for that.

Now why it is taking the key as the `0,1` and ... the answer of this question is hidden in the structure of the array. We know that array has the index values though that we can access the values of that array. That concept comes in this case also the keys are the index of that values and we can see that there is a length that tells us that what is the lenght of that object like array.

### Pop()

This method is used to remove the last element from the array and return that value and with that it reduce the lenght of that array.

There is a edge case comes into the picture that is if there is no element in the array then what will the output in that case. **<mark class="bg-yellow-200 dark:bg-yellow-500/30">The removed element from the array; </mark>** `undefined` **<mark class="bg-yellow-200 dark:bg-yellow-500/30">if the array is empty.</mark>**

Let's take an example of this

```javascript
const data = [1,2,3,4,5]
console.log(data.pop()) // 5
console.log(data.length) // 4
console.log(data) // [1,2,3,4]

const testing = []
console.log(testing.pop()) // undefind
```

As usual we can guss the result of this program. But when it comes to Object then it becames somthing different. Let's understand this through an example

```javascript
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.pop.call(arrayLike));
// 4
console.log(arrayLike);
// { length: 2, unrelated: 'foo' }
console.log(Array.prototype.pop.call(arrayLike)); // undefined
console.log(arrayLike); // {length: 1, unrelated: 'foo'}
```

I think that it is expectable because we already know that what is the behavoiur of array like object so in this case also the same thing is happening.

But where is the intresing thing comes into the picture let's check the example

```javascript
const arrayLike = {
  length: 2,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.pop.call(arrayLike));// undefined
console.log(arrayLike); // {2: 4, length: 1, unrelated: 'foo'}

console.log(Array.prototype.pop.call(arrayLike));// undefined
console.log(arrayLike); // {2: 4, length: 0, unrelated: 'foo'}
```

OMG why this is comming like this ? Why the element is there ? why the lenght is just decreasing ?

Let's understand the internal concept of this. So there is a property called lenght which stores the lenght of that array but here we assigned that lenght to 2 which means the pop methode is pointing to the `length-1` element but there is no key of `'1'` so as the behavior of js when there is no element at that position then it returns undefind as we are getting in the above example.  
So what we got to know from this that when the pop method is called then is go to the index of last element by performing the `lenght - 1` and simply remove that element and decress the lenght of the array. Wow that is amazing ritght.

## shift() and unshift()

### Shift()

So what is the work of this method ? this simplly remove the element from the front of that array. Is it possible to understand the topic with out any example i don't think so here is the example

```javascript
const data = [3,4,5,6,7]

console.log(data.shift()) // 3
console.log(data) // [4,5,6,7]
//  if the array is empty then what is going to happen are you able to predict 
const data2 = []

console.log(data2.shift()) // undefind
console.log(data2) // []
```

Are you able to predict the answer of this i think this is a normal think. This works as pop works the difference is just pop removes from the last but the shift removes from the first.  
Is it a mutating method ? The answer is yes this methode is a mutating method.

Now it comes to the object part what we are facing in above example😊.

```javascript
const data = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.shift.call(data));
// undefined, because it is an empty slot
console.log(data);
// { '1': 4, length: 2, unrelated: 'foo' }

const data2= {}; // lenght is 0 
Array.prototype.shift.call(data2);
console.log(data2);
// { length: 0 }
```

Is it a expected behavior of javascript and the answer is yes. Also you get that why the key changes because the empty element is got removed and the other elements index got reduced by 1.

## Unshift()

We get to know that the shift methode works like the pop() method so we can think that this unshift method will work like the push method but difference will that it will add the element from the front of that array. Let see the example.

```javascript
const data = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.unshift.call(data,2)); // 4 the lenght of that array
console.log(data); // {0: 2, 3: 4, length: 4, unrelated: 'foo'}

const data2= {}; // lenght is 0 
console.log(Array.prototype.unshift.call(data2,5)); // 1 the updated length  of that array like object 
console.log(data2); //{0: 5, length: 1} 
```

Is it mutating method ? Yes why the lenght got increased we are adding an element in the front and other elements are shifting to the right side of the array that why the indexs are also increased by 1.

## Map()

What is the work of this function you might wandering about this, so let's understanding about this methode Let's go.

So when we use this method in the array then it create a array according to the input operation and return that array as a result. So when ever we use this method then we have to pass a function like a arrow function, which can be applied into every element and return that newlly created array.

Our favorate part that is Example.

```javascript
const data = [1,2,3,4,5,6,7,8,9] // creating a new array 

let result = data.map((item) => item * 2);    // creating a new array and just multipling 2 with each item

console.log(data) // [2, 4, 6, 8, 10, 12, 14, 16, 18]
```

this is alll about this method there is not more then this but the arrow function can be canged according to your need it may became more complex or easy, but it always gona return a new array and that is your resulting array.

### Filter()

So what comes to your mind first when you hear this method, In my mind it hits like we have to separatre something from a group elements from an array. And the same thing comes to your mind then that is correct. Just a simple change is there and that is we have to just pass a condition with that function and that is called call back funtion the same concept is used in the map() also.

And its time for the example

```javascript
l = [1,2,3,4,5,6,7,8,9] // sample array for example 

ans = l.filter((item)=> item %2 == 0) // finding the even elements in the given array 
// what will be the output 
console.log(ans); // [ 2, 4, 5, 8 ]
```

I think you got it. If you are think that yes i got it then you are worng, Omg 😶‍🌫️😁sorry sorry.

Ok what we are missing, that is

It always return a shallow copy of that array. (Shallow copy means it passes the refrence of that result means the memory address)

example needed i think yes

```javascript
l = [1,2,3,4,5,6,7,8,9]

ans = l.filter((item)=> item %2 == 0)
ans[2] = 5
console.log(ans);
console.log(l); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

In this case it return a new array but when it comes to the array of the object then we can find that gocha.

```javascript
let l = [{a:1},{a:2},{a:3}];

let ans = l.filter(obj => obj.a > 1);

console.log(ans); // [ { a: 2 }, { a: 3 } ]

ans[0].a = 100; // changing the value of the ans 1st index 
// the ans should be [{a:1}, {a:2}, {a:3}]

// but the answer is changes as we discussed above 
console.log(l); // [{a:1}, {a:100}, {a:3}]
```

### Reduce()

Every one is thinking that it is a hard topic but it is not lets understand this with me. Think we dont know about this topic. Let's start, When the name comes what we should think that it is a method which helps us to calculate something and return that result. So what is takes, it take a call back function in which we passes the result(), iterator, and initialization of the result.

```javascript
const array = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

accumulator // result
currentValue // iterator 
initialValue // initialization
```

And this is the hole thing in this method. What you can do with this you can create a function or an arrow function and you can pass that function inside that reducs function.

Different type of application of reduce function.

```javascript
const getMax = (a, b) => Math.max(a, b);

// callback is invoked for each element in the array starting at index 0
[1, 100].reduce(getMax, 50); // 100

___________________________________________________________________________

const array = [15, 16, 17, 18, 19];

function reducer(accumulator, currentValue, index) {
  const returns = accumulator + currentValue;
  console.log(
    `accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
  );
  return returns;
}

array.reduce(reducer);
```

These are some types we can use this method.

### Foreach()

I think you can predict that what kind of work it will gona do, So it go from the first index to the last index with out any break(means we can't stop the loop in runtime). So how we can use this foreach loop? What did mean by this, it means how we can write the syntax for this.  
We can use the normal method and arrow funcion for this but an important thing comes into the picture that is foreach does not return anything, it does not support asynchronious means it is a syncronious process.

So now we can check the example of this foreach()

```javascript
let arr = [1,2,3];

arr.forEach(x => x * 2);

// it does not change the original value 
console.log(arr); // [1,2,3]
```

```javascript
let arr = [1,2,3];

arr.forEach((item, index, array) => {
  array[index] = item * 2;
});

console.log(arr); // [2,4,6]
```

As we know that we can create an function and pass as an argument.

Here we go we have learned some major topic or methods and learned many thing like how array internally works and how the mthods are working and a lot of things.
