Articles → JAVASCRIPT → Reduce Function In Javascript

Reduce Function In Javascript






Purpose







Example




<!DOCTYPE html>
<html>
<body>
    <script>
        const numbers = ["This", "is", "the", "test"];
        console.log(numbers.reduce(myFunc));

        function myFunc(call_back, element) {
            return call_back + " " + element;
        }
    </script>

</body>
</html>




call_backelementResult
"This""is""This is"
"This is=""the""This is the"
"This is the""test=""This is the test"


  1. The first element of an array is assigned to the "call_back" variable.
  2. The second element of an array is assigned to the "element" variable.
  3. An operation is performed as mentioned in the "myFunc" function.
  4. The result is stored in the "call_back" variable.
  5. The "element" variable is assigned with the third element of an array i.e. "the".
  6. Repeat steps 3 and 4.
  7. The "element" variable is assigned the fourth element of an array i.e. "test".
  8. The final result is displayed using the console.log function.

Output


Picture showing the output of the Reduce function in JavaScript

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, August 27, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250