
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- C program to find GCD of numbers using recursive function
- Swift Program to calculate the sum of all even numbers up to N
- C program to find GCD of numbers using non-recursive function
- Sum of even numbers from n to m regardless if nm JavaScript
- Using a recursive function to capitalize each word in an array in JavaScript
- How to create a function which returns only even numbers in JavaScript array?
- Sum of Even Numbers After Queries in Python
- Even index sum in JavaScript
- Sum of even Fibonacci terms in JavaScript
- Function to add up all the natural numbers from 1 to num in JavaScript
- Recursive sum all the digits of a number JavaScript
- Haskell Program to calculate the sum of all even numbers
- Golang program to calculate the sum of all even numbers
- Sum of individual even and odd digits in a string number using JavaScript
- 8085 program to find the sum of series of even numbers

Advertisements