Quickly Understand JavaScript .forEach() & jQuery .each() In 1 Minute

There are two functions to deal with an array on client-side – JavaScript .forEach() and jQuery .each(). Here, I will teach you how to use both of these methods with sample codes.

JavaScript .forEach() Method

The .forEach() method of JavaScript executes a given function once for each element of the array.

For example -

  1. var arr = ['a''b''c'];    
  2. arr.forEach(function(element) {  
  3.     console.log(element);  
  4. });  

The above JavaScript code will print – ‘a’, ‘b’, & ‘c’ in the console window.

jQuery .each() Method

jQuery has its own method to loop though an array. This is called jQuery Each Method- .each().

  1. var arr = ['a''b''c'];  
  2. $.each(arr , function (index, value){  
  3.   console.log(arr);   
  4. });  

The above jQuery code will print – ‘a’, ‘b’, & ‘c’ in the console window.

Which one to choose

Both of these above methods are very good and result in decreasing the coding lines as compared to the normal For Loop in JavaScript. They also make the code easy to understand.

If you are using jQuery, then prefer .each() method, else use .forEach(). But it is totally your own choice.


Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now