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_back | element | Result |
---|
"This" | "is" | "This is" |
"This is=" | "the" | "This is the" |
"This is the" | "test=" | "This is the test" |
- The first element of an array is assigned to the "call_back" variable.
- The second element of an array is assigned to the "element" variable.
- An operation is performed as mentioned in the "myFunc" function.
- The result is stored in the "call_back" variable.
- The "element" variable is assigned with the third element of an array i.e. "the".
- Repeat steps 3 and 4.
- The "element" variable is assigned the fourth element of an array i.e. "test".
- The final result is displayed using the console.log function.
Output