Skip to main content
Home / Articles /

What is Code “Golf”?

From the grand archives of "Things Chris was totally confused about for far too long and now half understands so might as well blog it": code golf. I would hear someone say something like "I got it down that small from my own golf." I would squint, confused, and just let it pass because it didn't seem important enough to ask about. Slang for "work", perhaps, or "tinkering".

That's not far off, really. The whole idea is reducing code down to as few characters as possible while remaining functional. In (real) golf, the fewer strokes to get the ball in the hole, the better you are doing. In code golf, the fewer characters you use, the better you are doing.

Sometimes code golf is a part of a competition (or tournament I suppose, keeping with the parlance). Sometimes it's just for fun. Sometimes it's useful. Sometimes the format is to solve a particular challenge or algorithm or achieve certain expected output from given input.

The understandability of "golfed" code goes right out the window. The code isn't supposed to be understood, it's supposed to be short and work. It's common to look at a bit of golfed code with complete bewilderment. Here's one:

function(a){a='0x'+a.slice(1).replace(a.length>4?a:/./g,'$&$&')|0;return[a>>16,a>>8&255,a&255]}

That's a bit of JavaScript to take a hex color and return the RGB values from it. Hard to tell just by looking at it! It's by Jed Schmidt, on his site 140byt.es which features tweet-sized bits of JavaScript that do functional things.

In the case of JavaScript, golfed code might be useful occasionally, since it's all the less code to send over the network.

Wikipedia has an article on code golf, saying it started with Perl in 1999. Just about any language you can think of you can golf (it's just a concept, after all) and probably even has a tournament. Both Reddit and StackExchange have dedicated subsites just for it.

Besides just being fun, it can be an exercise in developing a deeper understanding of the language as well as stretching your logic and reasoning ability.

Code golf doesn't have to be formalized, it might just be something you do for fun. When you shave a couple of lines of code off something you're working on, you golfed it.


As a bit of a relevant aside here, one language I haven't seen much golf in is SVG. SVG is kinda perfect for it though, as it's so mathematic, declarative, and referential. It was this Pen that got me thinking about it:

See the Pen Arrows by fuddl (@fuddl) on CodePen.

I tried my hand it a bit too:

See the Pen SVG Golf by Chris Coyier (@chriscoyier) on CodePen.