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
To find the factorial of a number multiply the number by every whole number less than it, down to 1.
The factorial of 0 is defined as 1.
0! = 1
0! = 1
1! = 1
2! = 2 × 1 = 2
3! = 3 × 2 × 1 = 6
4! = 4 × 3 × 2 × 1 = 24
5! = 5 × 4 × 3 × 2 × 1 = 120
6! = 6 × 5 × 4 × 3 × 2 × 1 = 720
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
Factorials are useful for counting the number of ways to arrange, combine, or select distinct items.
For example, how many different ways can n things be arranged?
Example:
How many ways can three books be arranged in a row?
3! = 3 × 2 × 1 = 6
There are 6 ways to arrange three books in a row.
3! = 6
Find the factorial of a given non-negative number using a for loop
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
Initialize a variable to hold given number n of the factorial.
const number = n; → user input
Define a function factorial that calculates the factorial of a given number.
function factorial(num) {}
The function takes a non-negative number as input, num and returns its factorial.
Base case
If num equals 0 or 1 return 1
if (num === 0 || num === 1) return 1
return 1 and end execution of function.
If num is greater than 1
Loop from num - 1 down to 1
for (let x = num - 1; x >= 1; x--) {}
Multiply num by x to compute the factorial.
num *= x num = num * x
Return computed factorial value.
return num
Call the function with ↴
factorial(number);
Find the factorial of 5
num = 5;
function factorial(num)
The function checks if num is 0 or 1
If it is, it returns 1 and ends execution of function.
If num is greater than 1 the function proceeds.
for (let x = num - 1; x >= 1; x--) {}
num *= x; num = num * x
First iteration of loop ↴
num → 5
x num - 1 → 5 - 1 → 4
x Iteration ↴
4 5 × 4 → 20
3 5 × 4 × 3 20 × 3 → 60
2 5 × 4 × 3 × 2 60 × 2 → 120
1 5 × 4 × 3 × 2 × 1 120 × 1 → 120
0 Loop ends and the calculated factorial of 5 is returned ↴
5! = 120
Find the factorial of 5
const number = 5;
function factorial(num) {
if (num === 0 || num === 1) return 1;
for (let x = num-1; x >= 1; x--) {
num *= x;
}
return num;
}
call function
factorial(number); returns ↴
120