The greatest common divisor is the largest number dividing both a and b. Euclid's algorithm, more than 2,000 years old, rests on one fact:
gcd(a, b) = gcd(b, a mod b), gcd(a, 0) = a
Any common divisor of a and b also divides a − k·b, so replacing a by a mod b keeps the same common divisors while the numbers shrink fast: O(log min(a, b)) steps.
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));