# Arrays In JavaScript

* * *

## what is an array ?

An Array is an object type designed for storing data collections.

Key characteristics of JavaScript arrays are:

*   **Elements**: An array is a list of values, known as elements.
    
*   **Ordered**: Array elements are ordered based on their index.
    
*   **Zero indexed**: The first element is at index 0, the second at index 1, and so on.
    
*   **Dynamic size**: Arrays can grow or shrink as elements are added or removed.
    
*   **Heterogeneous**: Arrays can store elements of different data types (numbers, strings, objects and other arrays).
    

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/e92ebdca-8e5b-4245-97f8-dc0b06555ab9.png align="center")

* * *

## Methods/Functions in Array

### push() & pop()

As the names suggest , push add elements and pop removes the elements. But do they add and remove elements from anywhere ? obviously NO

push adds element after the last index and pop too always remove the last element.

```javascript
let array=["hello","how", "may","help" ]
console.log(`${array} is the original array`) //used string interpolation
array.push("You ?")
console.log(`${array} has one more element`)
let deletedElement=array.pop()// you can retrieve the popped element
console.log(`${deletedElement} - last element removed \n updated Array ${array} `)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/0d573919-394a-4558-910e-451bfca9f61c.png align="left")

### shift() & unshift()

their work is same as pop and push respectively . Then why do they exist ? because they perform operations on first element .  
`At what index push/pop works ? if you have forgotten already revisit above.`

```javascript
let array=["hello","how", "may","help" ]
console.log(`${array} is the original array`) //used string interpolation
let newElement=array.shift()// you can retrieve the shifted element
console.log(`${newElement} - first element removed \nupdated Array ${array} `)
array.unshift("I")
console.log(`${array} has one element more`)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/12444158-1a25-45d8-ab16-c5a7b1eece80.png align="left")

> a little detour 🚞  
> before moving ahead You need to know about **higher order functions .**  
> **Nothing fancy just a function that accepts another function .**  
> that's it😉

### map()

map is a higher order function. Its work is simple

*   iterate ( move to one element at a time ) over array
    
*   pass each element as an argument to the function passed by user
    
*   pushes the output in new array
    
*   return that newly formed array
    

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/9946d022-f24f-4ce8-b3cc-8c4bcb27d41b.png align="left")

`imgsrc: Gemini`

```javascript
let array=[2,3,4,5]
let sum=function(number){
    return number*2
}
let doubleArray=array.map(sum)
console.log(`After doubling array:${doubleArray}`)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/ca9f0258-87fa-48d0-bcd9-8ca8f4276d2b.png align="left")

### filter()

also a higher order function . You should always be grateful when creators name jargons this easy resonating its true work . The function that a user passes should return either true or false for each element . All the elements for which the function returns true will be present in the new array (original remains untouched ) .

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/98bbf195-4ea5-4326-98ea-e448ddfbc2cd.png align="left")

`imgsrc:Gemini`

```javascript
let array=[2,3,4,5,7,9,8,10]
let isEven=function( number){
    return number%2===0
}
let evenArray=array.filter(isEven)
console.log(`Even array: ${evenArray}`)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/3824b495-f0f5-4a9e-8cd1-8ed5ed467d61.png align="left")

> If you are curious then you might be thinking that these simple task can be done using a for loop as well. You are definitely right .  
> what these higher order functions provide is code reusability and let you not to repeat your code.

### reduce()

yes a higher order function . yes it returns a reduced <s>array </s> ( not necessarily ) . the type of end result completely depends on what the user intends.

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/ebd41f17-eddf-4b66-88b5-06fcd239b5a3.png align="center")

```javascript
let array=[2,3,4,5,7,9,8,10]
let sum=function(total, number){
    return total+number
}
let totalNum=array.reduce(sum,0)//you have to give initial value of total ,                          //number will be the elements of array
console.log(`Sum of elements in array: ${totalNum}`)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/3df46503-3b50-46b8-bedd-358cd0fbb023.png align="left")

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/382a0250-221f-4a27-855f-5940ae540deb.png align="center")

`this image shows a representation of how a reduce accumulates values .`

Before you make your mind to limit the usage of reduce to only calculating sum of arrays ( which most of you already did ) , I want you to make a note of something:

*   is there any restriction on the initial value that it should be 0 or a number for that matter ?
    
*   is there any restriction on the function you can pass ?
    

Answer to both of them is strictly NO .

since most of the times you will be using to reduce an array to a single value (reduce) but that does not limits its implementations .

Eg :

```javascript
let menu=[{name:"Makhani dal" , isVeg:true},
          {name:"Shahi Paneer", isVeg:true},
          {name:"Biryani" , isVeg:false}
]
let veg=function(vegOnly, dish){
    if(dish.isVeg){
        vegOnly.push(dish.name)
    }
    return vegOnly
}
let pureVeg=menu.reduce(veg,[])//initial value passed is an empty array
console.log(`Pure veg items: ${pureVeg}`)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/70bf939a-a4c8-4fbb-a227-b9e1a4fcd8ed.png align="left")

from a menu of dishes i just filtered ( might use filter() ) veg dishes using reduce and returned an array not just a single value . And definitely you can also do anything .

### forEach()

higher order - yes , expects a function - yes

but does not return anything . It works similar to map() . Like a loop that passes elements to a function . So in this case your function does not return , but can do console log .

```javascript
let numbers=[ 3,6,4,5,7,8,9,12,10 ]
let isDivisbleBy3=function(number){
    if( number%3 === 0){
        console.log(`${number} is divisible by 3`)
    }
    else{
        console.log(`${number} is not divisible by 3`)
    }
}
numbers.forEach(isDivisbleBy3)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/c1a2bbb2-89ef-472e-b414-7e7e90866ff5.png align="left")

* * *

## Things you should try

*   you can pass arrow functions as well .
    
*   find what other parameters are allowed in the user function ? is it the just element or can be index as well and other things .
    
*   think of a practical use case like writing some logic for a restaurant website where can you these to implement features ? ( one is shown in reduce section -> up to you how you wanna implement it )
    
*   Bonus : you can actually build your own versions of these methods using protoype only in javascript . You can then use on arrays.  
    for your reference i made the hindi versions . this one is of filter and my version returns the array😜  
    

```javascript
//filter
Array.prototype.छलनी =function(userFunc){
   
    if(typeof userFunc != "function") return
    let newArray=[]

    for (let index = 0; index < this.length; index++) {
        const element = this[index];
        if(userFunc(element)) newArray.push(element)
    }
   return newArray
}
let nums=[2,3,5,4]
nums=nums.छलनी((ele)=>ele%2==0) 
console.log(nums)
```

![](https://cdn.hashnode.com/uploads/covers/6957f886be098e09544c295f/c25e16a6-119d-4283-935f-46c89c020fd8.png align="left")

* * *
