In this article, we’ll golf some JavaScript code. But first, we’ll need to know what the heck is code-golf?
Contents
What is code-golf?
Code golfing is trying to make the shortest possible code for a given task. It’s mainly a game and very useful for improving your programming skills. There are many sites where you can code golf. Here’s a list of some of the most popular sites:
Get started!
We’ll code-golf the easiest challenge that is Fizz-Buzz (https://code.golf/fizz-buzz). Our task is to print all the numbers from 1 to 100. But instead of printing the numbers, we’ll print the word “Fizz” if the number is divisible by 3, “Buzz” if the number is divisible by 5, and “FizzBuzz” if the number is divisible by both 3 and 5.
So first we’ll make a basic program that prints all the numbers from 1 to 100.
Now we can see all the numbers from 1 to 100. But we need to add the logic to print Fizz, Buzz, or FizzBuzz.
But that’s 240 bytes! Now we code-golf it!
Reduce the length of the for loop condition
The current for loop statement is:
We can remove the i++
part and replace i<=100
with i++<100
. So our for loop will look like this:
Now we reduced the code to 225 bytes.
Convert if-else to a single line
We can make the if-else statement into a single line using the ?
operator.
We removed 103 bytes.
let
keyword
Remove the Because we don’t use any scope, we can remove the let
keyword.
console.log
with print
Replace We can replace console.log
with print
and reduce the code to 112 bytes.
Fizz
Create a variable for saving We’ll create a variable like this.
Look at the below diagram.
Now we use this logic in the print
function.
Don’t get confused ?. Here’s how it works:
First, we check if i % 5
is not zero. That means i % 5
is not divisible by 5. So we again check if f
is empty. If f
is empty, we print i
else we print f
.
If i % 5
returns zero, that means i % 5
is divisible by 5. So we just print f + "Buzz"
.
And that will make our code look like this:
That’s 92 bytes.
print
function to the loop header
Move the We can move the print
function to the loop header.
And we can remove the {}
braces because there’s only one statement.
Our code is getting shorter and shorter. Now it’s 79 bytes.
Remove all spaces
This is the most basic thing, but I do it last.
Now we’ve made the shortest possible Fizz Buzz in JavaScript. Which is 56 bytes. You can try to make it shorter.