Tuesday, September 17, 2024

JavaScript each vs forEach


This article demonstrates how to use the ‘each()’ and ‘forEach()’ functions. The ‘each()’ function is part of the jQuery library, while ‘forEach()’ is a native JavaScript method. 


In the next section, we explain the two functions and demonstrate how to use them to iterate over different structures with jQuery and JavaScript code snippets. Note that these snippets are part of a complete code example, which can be found in the final section.


1. The ‘each’ Function

The jQuery ‘each()’ method is a versatile iterator used to loop over a collection of DOM elements, arrays, or objects. It simplifies the process of performing actions or applying logic to each item within a set, handling the iteration for you. 


The table below provides a summary of how the ‘each()’ method is used to iterate over objects and collections of elements, illustrated with examples.

Function

Iterates over

Code Snippet

Code Output

$.each

jQuery object

let person = {name: "Mary", age:22, email: "mary@gmail.com"};

$.each(person, function(key, value) {

console.log(key + ": " + value);

});

name: Mary

age: 22

email: mary@gmail.com

$.each

jQuery array

let arr_num = [4, 12, 20];

$.each(arr_num, function(index, value) {

console.log(index + ": " + value);

});


0: 4

1: 12

2: 20

$(selector).each

jQuery DOM elements

$('li').each(function(index, element) {

console.log('index: ' + index + ', element: '

+ $(element).text());

});


index: 0, element: li 1

span 1

index: 1, element: li 2

span 2

index: 2, element: li 3

span 3



$.each($('li'), function(index, element) {

console.log('index: ' + index + ', element: '

+ $(element).text());

});



index: 0, element: li 1

span 1

index: 1, element: li 2

span 2

index: 2, element: li 3

span 3


2. The ‘forEach’ Function

The ‘forEach()’ method is a built-in array method in JavaScript that allows you to iterate over arrays to execute a provided function once for each element in the array. This method provides a more concise and readable alternative to traditional ‘for’ loops.


The table below offers an overview of how the ‘forEach()’ method is used to iterate over arrays and ‘NodeLists’, accompanied by illustrative examples.

Function

Iterates over

Code Snippet

Code Output

forEach

JavaScript array

(Arrray.prototype.forEach)

let array_num = [1, 2, 3];

array_num.forEach(function(value, index, array) {

console.log('index: ' + index + ', value: ' + value);

});


index: 0, value: 1

index: 1, value: 2

index: 2, value: 3


JavaScript nodelist

(NodeList.forEach)

document.querySelectorAll('li').forEach(function(element, index) {

console.log('index: ' + index + ', element: '

+ element.innerHTML);

});


index: 0, element: li 1

<span>span 1</span>

index: 1, element: li 2

<span>span 2</span>

index: 2, element: li 3

<span>span 3</span>


3. HTML Example

The code snippets presented in the tables above are excerpts from the complete example provided below:


<!DOCTYPE html>

<html>

<head>

<style>

.wrapper * { 

  display: block;

  border: 1px solid grey;

  color: grey;

  padding: 5px;

  margin: 10px;

}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  //JQuery object

  let person = {name: "Mary", age:22, email: "mary@gmail.com"};

  $.each(person, function(key, value) {

    console.log(key + ": " + value);

  });

  

  //JQuery array

  let arr_num = [4, 12, 20];

  $.each(arr_num, function(index, value) {

    console.log(index + ": " + value);

  });



  //JQuery DOM elements

  $('li').each(function(index, element) {

      console.log('index: ' + index + ', element: ' + $(element).text());

  });


  //JQuery DOM elements

  $.each($('li'), function(index, element) {

      console.log('index: ' + index + ', element: ' + $(element).text());

  });



  //JavaScript array

  let array_num = [1, 2, 3];

  array_num.forEach(function(value, index, array) {

     console.log('index: ' + index + ', value: ' + value);

  });



  //JavaScript NodeList

  document.querySelectorAll('li').forEach(function(element, index) {

      console.log('index: ' + index + ', element: ' + element.innerHTML);

  });


});


</script>

</head>


<body class="wrapper">

  <div>

    <ul>ul 

      <li>li 1

        <span>span 1</span>

      </li>

      <li>li 2

        <span>span 2</span>

      </li>

      <li>li 3

        <span>span 3</span>

      </li>

    </ul>   

  </div>

</body>

</html>




No comments:

Post a Comment

Blog Posts

Enhancing Performance of Java-Web Applications

Applications built with a Java back-end, a relational database (such as Oracle or MySQL), and a JavaScript-based front-end form a common and...