Array methods in Javascript

Different array methods used in js.


ShankarAnand R

2 years ago | 1 min read

Bonjour tech-nerd !! In this blog we'll see about some important must known array methods of javascript.

Content1. Array in general2. Why methods?3. forEach()4. Map()5. Filter()6. Reduce()

Lets get started 🎉

1. Array

Array is a collection/list of data stored in a single variable.

Syntax1: const arrayName = new Array(item1, item2, item3...);

Syntax2: const arrayName = [item1, item2, item3...];

Array Creation & accessing:

const games = ["Football","Cricket", "Snake&Ladders","Ludo"];//indexingconsole.log(games[1]); //Books//using for-loopfor(let i=0;i<games.length; i++){ console.log(i);}//Output:FootballCricketSnake&LaddersLudo

2. Why methods?

Methods are predefinded function to access and modify array elements efficiently. There more array methods avialable. But we only see some.

3. forEach()

Basically for and forEach() both does the same this i.e to iterate through the array.The only difference is that forEach() uses callback function where for loops through the array sequentially.

const hobbie = ["Photography","Books", "Music"];hobbie.forEach((item)=>{ console.log(item);});
  • Output:


For vs forEach()

At the end of the day, both does the similar operation. It only depends on your personal preference.

4. Map()

map() method works same as the forEach but as the callback function hits every element it creates a new array with upcomming the result.

const nums = [1,2,3,4,5];var>{ return item*2;});console.log(result);

  • Output:[2,4,6,8,10]

5. Filter()

filter() method creates a new array from a given array which satisfy a given condition.

const nums = [1,2,3,4,5,6,7,8,9,10];var result=nums.filter((item)=>{ return (item%2==0); // returns even number});console.log(result);
  • Output:[2,4,6,8,10]

6. Reduce()

As the name insists reduce() method reduce the array to a single value as per the reducer function. It takes two required param total and current value.

// sumof all elementsconst nums = [1,2,3,4,5,6,7,8,9,10];const sum = nums.reduce((total, curr) =>{ //params can be named anything. return (total + curr);}); console.log(sum);
  • Output:55

Alright nerds! Thats it for now, hope it helped. Thanks for reading. Stay tuned!! See you👋.


Created by

ShankarAnand R







Related Articles