JavaScript bootcamp · Lab 22

Factorial function

mediumFunctions12 minLesson: Functions

Read the question, write JavaScript on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Write a function factorial(n) that returns n! (the product 1 × 2 × … × n). By definition 0! is 1.

The main part already reads n and logs factorial(n) — you only fill in the function.

Input. One line: an integer n ≥ 0.

Output. One integer: n!

Constraints

  • 0 ≤ n ≤ 18 (stays an exact integer).

Examples

Example 1 — 1×2×3×4×5.
Input
5
Output
120
Example 2 — The empty product is 1.
Input
0
Output
1
Hint
  1. Start result at 1 and multiply by every number from 2 to n.
  2. When n is 0 or 1 the loop body never runs, so result stays 1 — exactly right.
Show correct code

Peek only after you have tried. You can still Check your own version.

function factorial(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) result *= i;
  return result;
}

const n = Number(readLine());
console.log(factorial(n));
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.