Learn to Code via Tutorials on Repl.it!

← Back to all posts
Tips and Tricks for Code Golfing in JavaScript

Let's start off with the basics

What is code golf?

Code golf is a type of programming challenge in which the programmer must attempt to solve some challenges in the shortest number of characters possible. This may seem completely pointless and not applicable to the real world, and it is, but it's a fun exercise.

Tips and Tricks for Code Golfing

1. Write ungolfed code first - The most important thing is to have your program work. Character count should be a second priority. I recommend you write ungolfed, or normal, code first, and then try to make it shorter. A mistake I see many beginners make is they try immediately to start golfing their code and in the end they become frustrated why it throws a bunch of errors or gives the incorrect output. When code golfing, make sure it works first, then try to golf it.

2. Use ternary operators - Ternary operators are a shortcut for if else statements and are extremely useful. Not only can you shorten your existing if else statements, you can also assign variables and "return values" with them. Basically, how ternary works is condition ? execute_if_true : execute_if_false

As you can see, in the first example I am not console.loging directly inside the ternary, but rather using it to "return" the correct result and then logging the result. The second example demonstrates how to set variables using ternary. One thing to note is that both statements to execute if true and if false must be present. This means you cannot do something like this: a>b?console.log("hi") and skip the else condition. One way to get around it is just like this: a>b?console.log("hi"):0. Of course, the spaces between the ternary operators can be removed, which leads me to my next point.

3. Remove your whitespace

JavaScript's whitespace is not part of syntax which means you can remove it all. Compress all of your code onto one line by taking advantage of semicolons. This is a simpler point but still incredibly useful.

4. Use arrow functions

Arrow functions are useful both in normal programming and in code golf as they can shorten the code for anonymous functions. Instead of using function() {} for defining a function, you can simply use () => {} and pass parameters with param1 => {} or (param1, param2) => {}

5. Consider built-in functions

Often, a built-in function can shorten your code immensely. Some useful built-in functions include forEach, map, reduce, sort, and many more. I especially recommend forEach for iterating through arrays:


These are a few ways to improve your code golfing skills in the language of JavaScript. Code golf can be an incredibly fun challenge and is a good way to get more familiar with the programming language itself while teaching you new ways to think about problems.

TEST YOUR CODE GOLF SKILLS WITH ECOCODE: https://repl.it/talk/share/EcoCode-Competitive-Code-Golfing-Online/29877


I think I'll write a follow up to this.

  1. There is an even more slick way >:)

@Coder100 array.map(console.log) works too


This may seem completely pointless and not applicable to the real world, and it is...

Code golfing is incredibly important in interpreted languages, along with minification, it can speed up browser JavaScript noticeably.
Learn built-in functions completely:

Use anonymous objects wherever it shortens code:



@StudentFires err... there's quite a big difference between golfing and minifying. Let me explain: a golfer's goal is to make his code as short as possible without any regard to time complexity. if a solution that was O(n^5) was one character shorter than an O(n) solution, it would be preferred. Minifying is compressing your code in its current state to be as short as possible to decrease load time, not really to increase performance. the minifier doesn't alter the functionality of the code at all, merely makes it shorter. yes, during this process code performance may be marginally improved, however minifying is far different from golfing


@MrEconomical No, no... I understand that. I'm suggesting both.


@MrEconomical If you choose a solution that was O(n^5) over an O(n) solution because it was one character shorter, for production code, you don't know how to code.

If it's for code golfing, it doesn't matter.

There's a place in between where you improve performance and shorten size.


@StudentFires exactly my point; code golfing also might not be too relevant because minifiers exist


@MrEconomical Maybe... especially considering how JavaScript is compiled into byte-code by most major browsers.


@StudentFires @MrEconomical fyi some minifiers, including javascript ones golf to a safe extent, especially if you consider code wrangling golfing. meaning only operations guaranteed not to break input code are used. there's different ways to mangle and the more complex operations definitely do not provide behavior consistency guarantees for your application code - but my point is the minifier can alter code funtionality, especially if you're not careful. and, the 'golfing' example student fires presented is possible output when using current minifiers - it's not something that would be exclusive to code golfers


@eankeen the techniques of minifiers that some might also use for code golfing do save a lot of space, but this never translates to more than marginally faster application code - when cold starting a javascript application the bulk of the time is spent evaluating the code, not parsing it


@eankeen That's definitely interesting to know. Do you know of any specific minifiers that golf code?


@StudentFires the primary minifier that would have a side effect of appearing to golf your code would likely be a webpack and webpack's terser plugin (terser would be the minifier and webpack is just a module bundler). like i said the terser would wrangle the safe parts and webpack has options to wrangle esm/cjs imports under the optimizations object of its configuration. you would have to adjust other settings though, because webpack's bundles are usually larger since it's more careful about namespacing dependencies to prevent conflicts. you could go with a rollup and rollup-plugin-terser combo which should be good enough as well - like i said none of these programs are for specifically for golfing code, but they apply transformations to your code that could be considered golfing


Oooo ternaries


Fun but not a good thing to make code harder to read.


I would like to add that there are several ways to compact functions.
1. Use arrow notation.
2. Use eval instead of return.

So, for instance
function thing(input){ return input*3 }


@AtticusKuhn Umm, why wouldn't you just use t=i=>i*3?


Hmmm c macros