Checking Prime Numbers in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the topic of prime numbers in JavaScript programming. Specifically, we will learn how to check whether a given number is a prime number or not using a simple algorithm. This knowledge can be useful in a variety of applications, such as cryptography, data security, and number theory.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") subgraph Lab Skills javascript/variables -.-> lab-28437{{"`Checking Prime Numbers in JavaScript`"}} javascript/data_types -.-> lab-28437{{"`Checking Prime Numbers in JavaScript`"}} javascript/arith_ops -.-> lab-28437{{"`Checking Prime Numbers in JavaScript`"}} javascript/comp_ops -.-> lab-28437{{"`Checking Prime Numbers in JavaScript`"}} javascript/cond_stmts -.-> lab-28437{{"`Checking Prime Numbers in JavaScript`"}} javascript/loops -.-> lab-28437{{"`Checking Prime Numbers in JavaScript`"}} end

Function to check if a number is prime

To practice coding, open the Terminal/SSH and type node. This function checks if a given integer is a prime number. Here are the steps to check if a number is prime:

  1. Check numbers from 2 to the square root of the given number.
  2. If any of them divides the given number, return false.
  3. If none of them divides the given number, return true, unless the number is less than 2.

Here's the code to implement this function in JavaScript:

const isPrime = (num) => {
  const boundary = Math.floor(Math.sqrt(num));
  for (let i = 2; i <= boundary; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return num >= 2;
};

You can test the function by calling it with a number as an argument:

isPrime(11); // true

Summary

Congratulations! You have completed the Number Is Prime lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like