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 -
- var arr = ['a', 'b', 'c'];
- arr.forEach(function(element) {
- console.log(element);
- });
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().
- var arr = ['a', 'b', 'c'];
- $.each(arr , function (index, value){
- console.log(arr);
- });
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.