When I go out for drinks with my fellow engineers, we tend to have conversations about technical matters.
Last time we had a good talk about the shortest code for FizzBuzz. FizzBuzz is a common programming challenge often used in job interviews to assess a candidate’s basic programming skills.
“building the short code” is often associated with a concept called “code golf”. Code golf is a type of programming competition where participants strive to write the shortest possible code that solves a given problem.
The requirement of FizzBuzz
The requirements for FizzBuzz are as follows:
- The program should output numbers from 1 to 100.
- However, for multiples of 3, it should output “Fizz” instead.
- For multiples of 5, it should output “Buzz” instead.
- For numbers that are multiples of both 3 and 5, it should output “FizzBuzz.”
Basic answer
The most common answer is below.
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
The following code may be better for readability.
for (let i = 1; i <= 100; i++) {
let msg = "";
if (i % 3 === 0) {
msg = "Fizz";
}
if (i % 5 === 0) {
msg += "Buzz";
}
console.log(msg || i);
}
The shortest code (NOT RECOMMENDED)
Now let’s consider the shortest code. Ignoring readability, my priority is to create a minimal code, so it is not practical and I do not recommend its use for production. I have considered it only as an exercise for the brain.
Here is my idea.
[...Array(100)].forEach((_, i) =>
console.log(
((i + 1) % 3 ? "" : "Fizz") + ((i + 1) % 5 ? "" : "Buzz") || i + 1
)
);
The conditional branching part of the if statement has been replaced with a ternary operator. Also, I replaced for looping with [...Array(100)].forEach
.
Although less readable, This is the shortest code I could come up with.