
- 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
Listing all the prime numbers upto a specific number in JavaScript
We are required to write a JavaScript function that takes in a number, say n, and returns an array containing all the prime numbers upto n.
For example: If the number n is 24.
Then the output should be −
const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const num = 24; const isPrime = num => { let count = 2; while(count < (num / 2)+1){ if(num % count !== 0){ count++; continue; }; return false; }; return true; }; const primeUpto = num => { if(num < 2){ return []; }; const res = [2]; for(let i = 3; i <= num; i++){ if(!isPrime(i)){ continue; }; res.push(i); }; return res; }; console.log(primeUpto(num));
Output
The output in the console will be −
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
- Related Articles
- Prime numbers upto n - JavaScript
- Counting prime numbers from 2 upto the number n JavaScript
- Finding two prime numbers with a specific number gap in JavaScript
- Finding all possible prime pairs that sum upto input number using JavaScript
- Sum of all prime numbers in JavaScript
- Finding the k-prime numbers with a specific distance in a range in JavaScript
- Find all prime factors of a number - JavaScript
- Sum of all prime numbers in an array - JavaScript
- Prime numbers in a range - JavaScript
- The numbers 13 and 31 are prime numbers. Both these numbers have same digits 1 and 3. Find such pairs of prime numbers upto 100 .
- Digit sum upto a number of digits of a number in JavaScript
- Is the reversed number a prime number in JavaScript
- Counting the number of 1s upto n in JavaScript
- Prime numbers within a range in JavaScript
- Sum all perfect cube values upto n using JavaScript

Advertisements