DEV Community

Avnish Jayaswal
Avnish Jayaswal

Posted on • Updated on

javascript array for-each

javascript forEach() method calls a function once for each element in an array , callback function is not executed for array elements without values.

The javascript each method use a callback function for each element of an array with 3 parameters

1 – array item
2 – array index
3 – array

array item (value) parameter in for each loop

     const numbers = [1, 2, 3, 4, ];
     numbers.forEach((item) => {
       document.write(item) ;      // output 1 2 3 4
       document.write("<br />") ;
     }) ;

Enter fullscreen mode Exit fullscreen mode

optional parameter index in foreach method


      const numbers = [1, 2, 3, 4];
      numbers.forEach((item, index) => {
        console.log("Index: " + index + " Value: " + item);
      });

Output
Index: 0 Value: 1
Index: 1 Value: 2
Index: 2 Value: 3
Index: 3 Value: 4

Enter fullscreen mode Exit fullscreen mode

javascript array foreach using key and value

      const numbers = [1, 2, 3, 4];
      numbers.forEach((value, key) => {
        console.log("key: " + key + " Value: " + value );
      });

Enter fullscreen mode Exit fullscreen mode

javascript foreach object

    const obj = {
        name: "value1",
        rank: "value2",
      };

     Object.keys(obj).forEach((key) => {
        console.log(key, obj[key]);
      });

Output
name value1
rank value2
Enter fullscreen mode Exit fullscreen mode

The Object.values() function return an array with index and values


    const obj = {
        name: "Avy",
        rank: "Captain",
      };

      Object.values(obj).forEach((val) => {
        console.log(val);
      });

OutPut
Avy
Captain

Enter fullscreen mode Exit fullscreen mode

The Object.entries() function returns an array of entries. An entry is an array of length 2, where entry[0] is the key and entry[1] is the value


      const obj = {
        name: "Avy",
        rank: "Captain",
      };

      Object.entries(obj).forEach((entry) => {
        const [key, value] = entry;
        console.log(key, value);
      });

OutPut
name Avy
rank Captain

Enter fullscreen mode Exit fullscreen mode

JQuery Each Function


      const yourArray = [1, 2, 3, 4];

      $.each(yourArray, function (key, value) {
        console.log("key: " + key + " Value: " + value);
      });

Output
key: 0 Value: 1
key: 1 Value: 2
key: 2 Value: 3
key: 3 Value: 4

Enter fullscreen mode Exit fullscreen mode

Top comments (0)