Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of even numbers up to using recursive function in JavaScript
We have to write a recursive function that takes in a number n and returns the sum of all even numbers up to n.
Let’s write the code for this function −
Example
const recursiveEvenSum = (num, sum = 0) => {
num = num % 2 === 0 ? num : num - 1;
if(num){
return recursiveEvenSum(num - 2, sum+num);
}
return sum;
};
console.log(recursiveEvenSum(12));
console.log(recursiveEvenSum(122));
console.log(recursiveEvenSum(23));
console.log(recursiveEvenSum(10));
console.log(recursiveEvenSum(19));
Output
The output in the console will be −
42 3782 132 30 90
Advertisements