
- 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 all prime numbers in JavaScript
We are required to write a JavaScript function that takes in a number as the only argument. The function should find and return the sum of all the prime numbers that are smaller than n.
For example −
If n = 10, then the output should be 17, because the prime numbers upto 10 are 2, 3, 5, 7, whose sum is 17
Example
The code for this will be −
const isPrime = (num) => { let x = Math.floor(Math.sqrt(num)); let j = x; while (j >= 2) { if (num % j === 0) { return false; } j−−; } return true; }; const sumOfPrimes = (num = 10) => { let iter = num; let sum = 0; while (iter >= 2) { if (isPrime(iter) === true) { sum += iter; } iter−−; } return sum; }; console.log(sumOfPrimes(14)); console.log(sumOfPrimes(10));
Output
And the output in the console will be −
41 17 1060
- Related Articles
- Sum of all prime numbers in an array - JavaScript
- Sum of prime numbers between a range - JavaScript
- Express 18 as the sum of two prime numbers in all possible ways.
- Print prime numbers with prime sum of digits in an array
- Finding sum of all numbers within a range in JavaScript
- Listing all the prime numbers upto a specific number in JavaScript
- Sum of the first N Prime numbers
- Prime numbers after prime P with sum S in C++
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Prime digits sum of a number in JavaScript
- XOR of all Prime numbers in an Array in C++
- Product of all prime numbers in an Array in C++
- How to get the sum of the powers of all numbers in JavaScript?
- Prime numbers in a range - JavaScript
- Finding all possible prime pairs that sum upto input number using JavaScript

Advertisements