JavaScript Array forEach()

📔 : Java Script 🔗

forEach() method, Array में present हर एक element के लिए एक Callback Function call करता है। Callback Function दिए गए elements के order में ही run होता है।


forEach() function Array के प्रत्येक value को user defined callback function में send करता है।

Understanding Callback Function

Callback Functions वो function होते हैं जो किसी दूसरे function में as an arguments pass किये जाते हैं। और जिस function में ये pass किये जाते हैं उन्हें Higher - Order Function कहते हैं।
JavaScript Callback Functions


JavaScript Array forEach() Syntax

array.forEach(function(currentValue, index, array), value);

Parameters

  1. function(currentValue, index, array) | required : यह callback function Array के हर एक element के लिए run होता है। इसमें तीन Parameters pass किये जाते हैं।

    1. currentValue | required : Array element की current value . 
    2. index | optional : current element की index .
    3. array | optional : यह array object है , जिससे current element belong करता है।
  2. value | optional : यह value callback function में pass करने के लिए होती है , जिसे function में this variable के through access कर सकते हैं , अगर value pass नहीं करते हैं तो by default "undefined" जाता है।

  3. Return Value : यह new undefined return करता है।


JavaScript Array forEach()

File : js_array_forEach.html

CopyFullscreenClose FullscreenRun
<!DOCTYPE html>
<html>
  <body>
    <script>
      function myfun(value , index, arr)
      {
      	/*access 10 using this*/
      	document.write(value*this + "<br>");
      }
      var arr = [2, 5, 6, 8, 8];
      let new_arr = arr.forEach(myfun, 10);
    </script>
  </body>
</html>
Output
20
50
60
80
80

हालाँकि अगर आप चाहे तो , अलग function define करने की वजाय forEach() function में ही direct function call कर सकते हैं।

<!DOCTYPE html>
<html>
  <body>
    <script>
      var arr = [2, 5, 6, 8, 8];
      let new_arr = arr.forEach(function myfun(value , index, arr)
      {
      	/*access 10 using this*/
      	document.write(value*this + "<br>");
      }, 10);
    </script>
  </body>
</html>

ये भी same result ही produce करता है।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook