Skip to content
Sign upLog in
← Back to Community
Tips and Tricks for Code Golfing in JavaScript
Profile icon
hacker
has Hacker Plan
eco27

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.

image

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

// No ternary if (a > b) { console.log("bigger") } else { console.log("smaller") } // With ternary console.log(a>b ? "bigger" : "smaller")

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.

console.log(1);console.log(2);console.log(3)

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) => {}

setTimeout(() => { console.log("hi") }, 500)

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:

array = [1, 2, 3, 4, 5] array.forEach(a => console.log(a))

Closing

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

Voters
Profile icon
programmeruser
Profile icon
leemlam
Profile icon
Stallone969
Profile icon
manzur1990
Profile icon
LukasKybartas
Profile icon
Tsadema
Profile icon
GJessica
Profile icon
LordPancake
Profile icon
mat1
Profile icon
amasad
Comments
hotnewtop
Profile icon
Zavexeon

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

Profile icon
Coder100
  1. There is an even more slick way >:)
array = [1, 2, 3, 4, 5] for(a of array)console.log(a)
Profile icon
pyelias

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

Profile icon
Coder100
Profile icon
xxpertHacker

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:

setTimeout(console.log, 500, "hi")

Use anonymous objects wherever it shortens code:

array = [1, 2, 3, 4, 5] array.forEach(a => console.log(a))

->

[1, 2, 3, 4, 5].forEach(a => console.log(a))
Profile icon
xxpertHacker

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

Profile icon
xxpertHacker

@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.

Profile icon
xxpertHacker

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

Profile icon
hyperupcall

@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

Profile icon
hyperupcall

@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

Profile icon
xxpertHacker

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

Profile icon
hyperupcall

@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

Profile icon
SixBeeps

Oooo ternaries

Profile icon
SuzyAC

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

Profile icon
AtticusKuhn

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 }
becomes
t=i=>eval(i*3)

Profile icon
xxpertHacker

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

Profile icon
Highwayman

Hmmm c macros