Numbers are used to represent both integer and floating-point values.
Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴
let num1 = 5; → number
let num2 = 2.5; → number
let num3 = num1 + num2;
console.log(num3); returns ↴
7.5 → number
Check if number is prime using ↴
for loop → executes a block of code a number of times.
modulo operator % (remainder operator) → returns the remainder left over when one operand is divided by a second operand.
for loop repeatedly executes a block of code until a specified condition evaluates to false.
The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.
for (let x = 0; x < 4; x++) {
console.log(x);
}
Loop variable x is initialized to 0
Condition x < 4 is checked before each iteration.
The loop will continue to run as long as x is less than 4
The loop repeatedly executes a block of code 4 times, from 0 to 3
For each iteration of the loop, the current value of x is printed to the console.
After each iteration, x is incremented by 1 x++
When x reaches 4 the condition evaluates to false, terminating the loop.
0
1
2
3 → printed to console
Modulo operator % (remainder operator) returns the remainder left over when one number is divided by a second number.
10 % 2 → remainder 0
10 % 3 → remainder 1
10 % 4 → remainder 2
10 % 5 → remainder 0
10 % 6 → remainder 4
10 % 7 → remainder 3
10 % 8 → remainder 2
10 % 9 → remainder 1
10 % 10 → remainder 0
10 % 2 === 0 → 10 is divisible by 2
10 % 5 === 0 → 10 is divisible by 5
10 % 10 === 0 → 10 is divisible by 10
Initialize a variable to hold the number to check if it is prime.
const number1 = 17; → user input
Define a function isPrime to check if number is prime.
function isPrime(num) {}
The function takes a number as input num and returns true if number is prime, otherwise it returns false.
If num is less than or equal to 1, it is not prime.
if (num <= 1) return false
If true, return false and end execution of function.
If num greater than 1, loop through all numbers from 2 to num - 1
for (let x = 2; x < num; x++) {}
For each iteration, use the modulo operator to check if num is divisible by x
if (num % x === 0) return false
If true, it is not prime.
If it finds any divisor, return false and end execution of function.
If the loop completes without finding any divisors, num is a prime number. Return true.
return true
If the function returns true, the number is a prime number ✔
If the function returns false, the number is not a prime number ✖
Call the function with ↴
isPrime(number1);
Check if number is prime.
const number1 = 17;
function isPrime(num) {
if (num <= 1) return false;
for (let x = 2; x < num; x++) {
if (num % x === 0) return false;
}
return true;
}
call function
isPrime(number1); returns ↴
true
Number 17 is a prime number, function will iterate from 2 to num - 1 → 15 times.