Sign up ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

What general tips do you have for golfing in JavaScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to JavaScript (e.g. "remove comments" is not an answer).

Note: Also see Tips for Golfing in ECMAScript 6

share|improve this question
I was actually wondering, is it allowed to put variables in global (saves var)? And should JavaScript golf code be a function or output something directly? I honestly think this can make much difference. – pimvdb May 27 '11 at 5:28
@primvdb: It is allowed, but you have to be careful because it can cause side-effects if a function is called multiple times and it is manipulating global variables, or if it is a recursive function. – mellamokb May 27 '11 at 13:44

58 Answers 58

up vote 57 down vote accepted

Fancy For Loops

you can use the standard for loop in non-standard ways

for ( a; b; c )

is essentially equivalent to:

while ( b )

so a good trick is to write your code with a while loop, and then split it into the a,b,c parts in a for loop.

A couple examples I've written:


Chain your setters

If you're initializing or resetting multiple values, chain the value to all the variables that need it:


Implicit Casting

Don't check your types, just use them as they are. parseInt() costs 10 characters. If you need to cast out of a string, be creative:

c = a + b; //failure
c = parseInt(a) + parseInt(b) //too long

c = -(-a-b); //try these
c = ~~a+~~b;
c = +a+ +b;
c = a- -b;

Avoid Semicolons

JavaScript has automatic semi-colon insertion. Use it often and well.


Save on brackets by shoving as much as possible into single lines, or parameters:

a( realParam1, realParam2, fizz='buzz' )

Increment/Decrement operators

a = a - 1;


a = a - 1;

can easily be rewritten as





Use this or self instead of window in global context

self explanatory 2 character savings.

Use Array-Access for repeat function calls

This is definitely a balancing act between variable/function name length and number of invocations. Instead of calling a.longFunctionName() twice, it's shorter to save the name and call the function via array-access:




this is especially effective with functions like document.getElementById which can be reduced to d[e]().


For a single call, the relative cost* is 8 + name.length characters. Each subsequent call has a relative cost of 2 characters.

For standard invocation, all calls cost name.length characters.

Use this method if 8 + name.length + (2 * invocations) < invocations * name.length

i = invocations len = minimum function length to get advantage

i | len
1 |  ∞
2 | 12
3 |  7
4 |  6
5 |  5
6 |  4

* relative cost doesn't include the calling object, perens, or parameters. Essentially: a.XXX() vs a[XXX]()

share|improve this answer
c = ~~a-~~b should be c = ~~a+~~b. Also, you can implicitly cast to integer using |0, for example Math.random()*6|0. – mellamokb Jun 1 '11 at 19:48
It's cheaper to coerce a string to a number with the unary plus operator. If a and b are strings, you can do +a+b to convert to number and add them. – Peter Olson Dec 2 '11 at 21:38
Where can I add ? – Inkbug Aug 1 '12 at 10:23
I swear I'm going to use d- -b in my code someday... – Jan Dvorak Dec 19 '13 at 14:21
+a+b doesn't work (at least on mine...) // a="1",b="1",+a+b // gives "11" – imma Jan 16 '14 at 11:46

Splitting with numbers to save the quotemarks:

"alpha,bravo,charlie".split(",") // before
"alpha0bravo0charlie".split(0)   // after
share|improve this answer
+1 for the stupidest trick ever. I lol'd. – R Porter Feb 22 '14 at 2:33
It works, and I've used it for multiple digits. – impinball Feb 12 at 3:55
Lol this is actually pretty creative – NiCk Newman Nov 3 at 19:37

You can use the object literal form of get/set to avoid using the keyword function.

var obj = {
  get f(){
    console.log("just accessing this variable runs this code");
    return "this is actually a function";
  set f(v){
    console.log("you can do whatever you want in here, passed: " + v);

1 && obj.f; // runs obj.[[get f]]
obj.f = Infinity; // runs obj.[[set f]](Infinity)
share|improve this answer
the getter/setter part was really helpful. thx – gion_13 Mar 14 '12 at 10:01
Actually, even better is an object method, if you only use it <= 2 times. On the other hand, arrow functions are far better at cutting down characters, as they serve almost the same purpose, and classes are rarely useful in golfed code. – impinball Feb 12 at 3:57

Use the comma operator to avoid braces (also applies to C):


Instead of


which is one character longer.

share|improve this answer
Is the semicolon necessary at the end of the first sample? – wjl Aug 20 '12 at 6:12
@wjlafrance: It would only not be required if it's at the end of the one-liner. – mellamokb Aug 20 '12 at 14:57

Taking advantage of short-circuit operators

Rather than long if statements or using ternary operators, you can make use of && and || to shorten your code. For instance:

var match = RegExp('[?&]' + name + '=([^&]*)').exec(;

return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;

can become

var match = RegExp('[?&]' + name + '=([^&]*)').exec(;

return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

The || operator is often used in this way for setting defaults:

evt = evt || window.event;

This is the same as writing

if (!evt)
    evt = window.event;

Creating repetitive strings using Array

If you want to initialize a long string of a particular character, you can do so by creating an array with a length of n+1, where n is the number of times you wish to repeat the character:

// Create a string with 30 spaces
str = "                              ";

// or
str = Array(31).join(" ");

The larger the string, the bigger the saving.

Parsing numbers

Use + and ~ operators instead of parseFloat() or parseInt() when coalescing a string type that is just a number to a number type:

var num = "12.6";
parseFloat(num) === +num;  // + is 10 characters shorter than parseFloat()

var num2 = "12"
parseInt(num2) === +num2;   // + is 8 characters shorter than parseInt()

var num3 = "12.6"
parseInt(num3) === ~~num3;  // ~~ is 7 characters shorter than parseInt()

var num4 = "12.6"
parseInt(num4) === num4|0;  // |0 is 7 characters shorter than parseInt()

Be wary though, other types can be coalesced with these operators (for instance, true would become 1) an empty string or a string containing just white space would become 0. This could be useful in certain circumstances, however.

share|improve this answer
+1 for Creating repetitive strings using Array - hadn't thought about that one. – mellamokb Jun 9 '11 at 15:04
To create repetitive strings, in ES6 you can use str.repeat(count) – Oriol May 12 at 16:38

This one is lesser known and lesser used, but can be impressive if used in the right situation. Consider a function that takes no arguments and always returns a different number when called, and the returned number will be used in a calculation:

var a = [ 
    /* etc... */ 

You might normally shorten this function using a single-letter variable name:

var r=Math.random,a=[r()*12|0,r()*11|0,r()*10|0,r()*9|0,r()*8|0,r()*7|0,r()*6|0,r()*5|0];

A better way to reduce the length is by abusing valueOf, which gives you a saving of 2 characters per invocation. Useful if you call the function more than 5 times:

var r={valueOf:Math.random},a=[r*12|0,r*11|0,r*10|0,r*9|0r*8|0,r*7|0,r*6|0,r*5|0];
share|improve this answer
Or, you could do it like either of these: let a=[5,6,7,8,9,10,11,12].map(x=>x*Math.random()|0) or let a=Array(7).map((_,i)=>i*Math.random()|0+5), 36 or 42 bytes saved, respectively. – impinball Feb 12 at 4:05
Is it possible to replace r(), or make it shorter? – NiCk Newman Nov 3 at 19:46

Sneak variable initialization into the prompt() call for getting user input

n=prompt(i=5);     // sets i=5 at the same time as getting user input

instead of using


As a side-effect, it displays the input value in the prompt window while saving 1 character.

share|improve this answer
This can also be applied to any function that doesn't accept arguments. – Casey Chu Jun 19 '11 at 21:59
Even when the function accepts arguments it can be useful, as in [1,2,3].join('',i=5) in cases where it saves a pair of braces. – DocMax Jun 30 '11 at 0:58
@DocMax: You could use comma operator for that - i=5,[1,2,3].join(). – xfix Jan 4 '13 at 11:59
@GlitchMr: I could, but it doesn't save any characters. I agree that most of the time that will be cleaner. I think there may still be cases where my ordering might save a char, although I cannot come up with one at the moment (and I may well be wrong). – DocMax Jan 4 '13 at 17:01
@DocMax Only if you are taking advantage of ASI. – impinball Feb 12 at 4:10

Shorter random number generation

If you need a random boolean (0 or 1):

new Date&1 // equivalent to Math.random()<0.5

If you need a random integer 0 <= n < 1337:

new Date%1337 // equivalent to Math.floor(Math.random()*1337))

This works because a Date is stored internally in JavaScript as the amount of milliseconds since an epoch, so the new Date is being coerced into 123somebignumber456 when you try to do integer math on it.

Of course, these "random" numbers really won't be as random, especially if you call them multiple times in quick succession, so keep that in mind.

share|improve this answer

Converting a while loop into a for loop is often equivalent:


But the second form can have variable initialization combined:


Notice the second form is one character shorter than the first form.

share|improve this answer
Or, even better, just use for loops. There's really no case where using a for loop results in larger code, as far as I have experienced. – impinball Feb 12 at 4:08

If you can accept Spidermonkey (for now) specific scripts, you can use ECMAScript 6 arrow functions. Insteading of writing code like the following.{return x*2}) // function? return?

You can shorten it like this.>x*2)
share|improve this answer

Use a bitwise operation to round a number toward zero:

// do this

// or do this

(Source: Random dice tipping)

Operator precedence determines which will be shorter in your program.

share|improve this answer
This can also be used to coalesce a string input into an integer, i.e., n=prompt()|0. – mellamokb May 27 '11 at 13:31
bitwise is also super fast compared to math.floor : – vsync Jun 7 '11 at 22:33
@vsync: Weird. I get math.floor to be about twice as fast as bitwise on Chrome 11.0.696.77. – mellamokb Jun 8 '11 at 11:47
very weird. for me they are both more or less same speeds & super fast in Chrome, but in FF the bitwise is a lot faster than Chrome, and Math.floor is terribly slow..almost should not be used I would say. – vsync Jun 8 '11 at 16:15
To keep the comments up-to-date, in current Fx they're both fast & about equal. Not that it's likely to be a bottleneck in the first place, compared to surrounding code... – FireFly Feb 1 '14 at 20:13

If you're initializing a variable to 1 in every iteration of a loop (for example, resetting a variable in an outer loop for an inner loop), like the following (from my answer to this question):


Since the result of a condition like j++<=n is 1 whenever its true, you can just assign the condition directly to the variable (because when it becomes false, the loop will stop executing and will no longer matter):


You can usually save 2 characters using this method. Regards to @ugoren for the idea in the comments to that answer.

For another example, I also applied this trick to my answer here with the expression w=r=++c<S.length in my outer for loop, saving a total of 4 characters.

share|improve this answer

Unicode shortcuts

If you use a hell of a built-in property at a big golfing challenge you can alias every property to a one character equivalent:


After executing the code above you can use it like this:
"foo".Č(/.*/,'bar') // replaces foo with bar

It may be browser dependent and i'm not sure if it's shorter than with(Array){join(foo),...} or defining variables as used properties with(Array){j=join,m=map...} but still it is worth mentioning.

    Math        Number              String              Array

ø   toSource    prototype           prototype           prototype
ù   abs         NaN                 quote               join
ú   acos        POSITIVE_INFINITY   substring           reverse
û   asin        NEGATIVE_INFINITY   toLowerCase         sort
ü   atan        MAX_VALUE           toUpperCase         push
ý   atan2       MIN_VALUE           charAt              pop
þ   ceil        MAX_SAFE_INTEGER    charCodeAt          shift
ÿ   clz32       MIN_SAFE_INTEGER    contains            unshift
Ā   cos         EPSILON             indexOf             splice
ā   exp         isFinite            lastIndexOf         concat
Ă   floor       isInteger           startsWith          slice
ă   imul        isNaN               endsWith            filter
Ą   fround      toInteger           trim                isArray
ą   log         parseFloat          trimLeft            lastIndexOf
Ć   max         parseInt            trimRight           indexOf
ć   min         length              toLocaleLowerCase   forEach
Ĉ   pow         name                toLocaleUpperCase   map
ĉ   random      arguments           normalize           every
Ċ   round       caller              match               some
ċ   sin                             search              reduce
Č   sqrt                            replace             reduceRight
č   tan                             split   
Ď   log10                           substr  
ď   log2                            concat  
Đ   log1p                           slice   
đ   expm1                           fromCharCode    
Ē   cosh                            fromCodePoint   
ē   sinh                            localeCompare   
Ĕ   tanh                            length  
ĕ   acosh                           name    
Ė   asinh                           arguments   
ė   atanh                           caller  
Ę   hypot           
ę   trunc           
Ě   sign            
ě   cbrt            
Ĝ   E           
ĝ   LOG2E           
Ğ   LOG10E          
ğ   LN2         
Ġ   LN10            
ġ   PI          
Ģ   SQRT2           
ģ   SQRT1_2         
share|improve this answer
I'm using google chrome, and these are all giving undefined. – SuperJedi224 May 14 at 19:19
It must be very firefox specific then. Sorry for the inconvenience. – bebe May 15 at 16:44

Combine nested for loops:

// before:

// after:

Example with different values for i/j:

// before:

// after:
share|improve this answer
(I've edited a) minor typo, but very clever! Note that this will only work on nested loops of same length (unless I'm wrong). – Camilo Martin Dec 18 '12 at 13:26
@CamiloMartin No, the loops don't need to be of equal length. The resulting number of iterations is i*j and the division/modulus operators retrieve the individual values of i and j. – user113215 Dec 19 '13 at 0:38
@user113215 You're right, awesome! :) I've edited the answer to include an example. – Camilo Martin Dec 19 '13 at 14:14

Something worth noting is that you can use a string in place of zero in some instances to save a couple of bytes here and there in loops:

// s="123456789", i=10
share|improve this answer
I tried ""++ in the console earlier wondering if it would work, of course it has to be in a variable first. Thanks! – Vartan Jul 30 at 21:00

tl;dr: Use ES6 features!

Arrow functions


s = x => x*x
// s = function (x) {
//   return x * x;
// }

for of


a = [1, 2, 3, 4];
[x for (x of a)]; // 1,2,3,4

Note: Using generators can save map calls

a = [1, 2, 3, 4];
b = [for (x of a) s(x)]; // 1,4,9,16
share|improve this answer
Arrow functions were already mentioned on Oct 13 '13 at 15:42. But that for..of is cool. Even shorter than for – manatwork Jan 7 '14 at 15:11
The array comprehension syntax seems to be wrong. According to the documentation should be like in Python: b = [s(x) for (x of a)]. – manatwork Jan 7 '14 at 15:15
@manatwork The above samples run fine in Traceur's REPL – Florent Jan 7 '14 at 15:31
No idea about Traceur, but you mentioned ECMAScript and pointed to Mozilla documentation. And array comprehensions in none of them looks like you wrote it. – manatwork Jan 7 '14 at 15:39
Array comprehensions were actually pulled midway through. – impinball Dec 3 '14 at 22:20

Looping Tip I

You can save 1 character when looping by changing the i on the last time used:

//not so god


Note: works with -- too (but modify the loop accordingly to avoid infinite looping)

Looping Tip II

There are certain scenarios where you can save one character by playing with the incrementing operator and values:


Note: you need to pay attention when for example 0 to -1. and 9 to 10, 99 to 100, so play around until you find a way to save the character

share|improve this answer
Your first example should do i++ and not ++i – Pierre Arlaud Nov 27 '13 at 16:22

Exception abusing

in case string/character literals are prohibited, you can use a try catch block:


now str equals "something"

if more strings are needed you can chain it with a number (e.g. zeros)


now arr equals ["something", "foo", "bar", " is not defined"]

share|improve this answer

Use Mozilla's nonstandard "expression closures" feature to save many characters in a script that only needs to work in the SpiderMonkey/Firefox or Rhino engines. For example,

function foo(){return bar}


function foo()bar

See the Stack Overflow page for more such tricks.

share|improve this answer
That's not Javascript. That's a SPACE STATION!!! – Thomas Eding Aug 20 '11 at 0:40
ECMAScript 6 to the rescue! ->bar – Ryan O'Hara Jun 10 '12 at 18:53
ECMAScript 6: let foo = () => bar;, ironically shorter than the golfed code above. – impinball Feb 12 at 4:41

In cases where you are using the ternary operator to chose between two numbers, and the conditional is either a boolean or number 1 or 0, you can do math operations instead:

(x ? num1 : num2) conclusions:

    1)if num1 equals num2, there ARE savings
    2)if num1 is (+1) or (-1) than num2, there ARE savings
    3)if either num1 or num2 equals to 0, there ARE savings
    4)it is MORE LIKELY to find greater savings on num1>num2 instead of num1<num2
    5)in method (*A) and (*B), savings are NOT GUARANTEED

            ex1: (x?5:4) to (x+4)
            ex2: (x?8:7) to (x+7)
            ex1: (x?3:0) to (x*3)
            ex2: (x?7:0) to (x*7)
            (*A) or (*B) //one might be shorter

            ex1: (x?4:5) to (5-x)
            ex2: (x?7:8) to (8-x)
            ex1: (x?0:3) to (!x*3)
            ex2: (x?0:7) to (!x*7)
            (*A) or (*B) //one might be shorter

            ex1: (x?5:5) to (5)
            ex2: (x?-3:-3) to (-3)

    (*A) use ((x*(num1-num2))+num2)
        ex1: (x?8:4)   to ((x*4)+4)
        ex2: (x?4:8)   to ((x*-4)+8)

        ex3: (x?6:-4)  to ((x*10)-4)
        ex4: (x?-4:6)  to ((x*-10)+6)

        ex5: (x?4:-6)  to ((x*10)-6)
        ex6: (x?-6:4)  to ((x*-10)+4)

        ex7: (x?-5:-9) to ((x*4)-9)
        ex8: (x?-9:-5) to ((x*-4)-5)

    (*B) use ((!x*(num2-num1))+num1)
        ex1: (x?8:4)   to ((!x*-4)+8)
        ex2: (x?4:8)   to ((!x*4)+4)

        ex3: (x?6:-4)  to ((!x*-10)+6)
        ex4: (x?-4:6)  to ((!x*10)-4))

        ex5: (x?4:-6)  to ((!x*-10)+4)
        ex6: (x?-6:4)  to ((!x*10)-6)

        ex7: (x?-5:-9) to ((!x*-4)-5)
        ex8: (x?-9:-5) to ((!x*4)-9)

Note: In addition to this, you will need to remove the unnecessary 0-, +0, +- etc.

Note2: there is an isolated case where (x) !== (x?1:0), as x must be typeof === "number" for it to work. However, in the case of (-x) it works just fine.

Note3: In case you don't find savings, simply use the former (x?y:z)

Previously I thought method B couldn't ever beat A, however exceptions do exist:

(x?97:100) //original


I created a github project that makes the simplification for us (jsFiddle demo)

share|improve this answer
@ajax333221 void 0 (it isn't a function, but a keyword) is not a value, it simply returns undefined. – Camilo Martin Dec 18 '12 at 12:07
@CamiloMartin you are right, also I now see the point in this answer, however a must be either 1 or 0 for it to work – ajax333221 Dec 18 '12 at 16:30
@ajax333221 Yes, actually the funny thing about code golfing to me is that most of the best tricks only work for that particular thing you're doing, and one feels so clever to find one of these corner cases with corner solutions :D By the way, you don't have to delete comments... – Camilo Martin Dec 19 '12 at 2:07

Transforming to a Boolean:


Note: This changes 0, "",false, null, undefined and NaN to false (everything else to true)

share|improve this answer

for a given array, we know a loop might lead to errors because stuff might be added to the Array.Prototype, so we revert to a normal for loop:

So instead of this iteration:

for (var i=0; i<arr.length; i++ )

lets do this:

for (var i=arr.length; i--; )

if we just want to iterate the Array not caring it goes backwards

share|improve this answer
Nicely found, but var can be dropped here as well I guess. Secondly, I honestly don't think you'd add functions to Array.prototype when golfing. – pimvdb Jun 7 '11 at 20:12
var makes the counter a local and not global variable, and globals are considered bad – vsync Jun 7 '11 at 21:17
Oh well I don't know, but that was the reason of the downvote of my post here :) – pimvdb Jun 8 '11 at 6:01
Indeed globals are considered bad in general JavaScript programming. But in code-golfing, it saves 4 characters which is never bad :-) In code golfing, you're generally breaking a lot of readability and usability rules anyway to squeeze out the last character. – mellamokb Jun 8 '11 at 11:53
@vsync: It seems like you're missing the point of golfing. Golf code isn't supposed to be readable, flexible, reliable or even maintainable. It's not for practical application, but just for fun challenges. Coding standards don't matter at all - all that matters is making your code short. – kba Nov 29 '11 at 6:07

Sometimes declaring a variable (or more) as function parameters can save some strokes by avoiding the var keyword. This use case is fairly rare though:

function f(){var i} => function f(i){}

Also you can use short circuit operators to avoid if statements:

if(a)b => a&&b

if(!a)b => a||b

To coerce to a number: str-0

share|improve this answer

If you need to check for NaN, don't use isNaN(x), but use x!=x, which is shorter and also works.

share|improve this answer

Repeated characters

Be creative when trying to repeat the same character:


With ES6, this becomes even shorter:


Note: It is unlikely that you use it to form a string, but the idea can be applied to form large numbers too

share|improve this answer
new could be dropped; the Array constructor called as a function does the same as if it's called as a constructor. If the character to repeat is unimportant, it could be left out and it'll default to ",". – FireFly Aug 30 '12 at 21:59

Initialize arrays with [] instead of Array(), and add to arrays with [.length]:

a=[];       // initialize a new array
a[0]=15;    // insert element to end of array
a[1]=30;    // insert another element to end of array
share|improve this answer
note: I know this is obvious, but if we are going to insert elements too close to index 0, it might be good idea to write it like this a=[15,30]; – ajax333221 Dec 18 '12 at 16:36
You can also leave elements undefined (say if you want a 2 indexed version of the above -> a=[,,15,30];. Also, I think you're suggesting adding things to the array using a[a.length]=x, but a.push(x) is shorter... – Alconja Aug 7 '14 at 1:59
Not a[a.length]. @Alconja is correct in suggesting a.push. – impinball Feb 12 at 4:42

Treat strings like you do C Strings.

Given s="hello"


is equivalent to



share|improve this answer
This is EcmaScript 5, but for code golf it's fine. – xfix Jan 4 '13 at 12:03
@xfix Yes, it's defined in EcmaScript 5, but Firefox has supported it from version 0.9. – Toothbrush Feb 24 '14 at 10:37

How to compare a number with help of how numbers turn into booleans:

If you are going to check if something is equal to a positive number, you can subtract that amount and reverse what was inside the if and else blocks:

//simplified examples:
x==3?"y":"n"; <- 13 Chars
x-3?"n":"y"; <- 12 Chars

//expanded examples:


And in case you are wanting to compare with a negative number (*different than -1), you just simply need to add this number instead of subtracting.

*well, you can surely use x.indexOf(y) + 1, but in the special case of -1 you have the opportunity to use ~x.indexOf(y) instead.

share|improve this answer

There's a few other ideas that come to mind:

Ternary operators with functions

Ternary operators also work well as a substitute for if..then..else statements with functions...


can be replaced with


You can take this further by abusing functions that don't take parameters:


If a, b, and d are numbers, you can use subtraction to test for 0.


Decimal Base Exponents

Another is the reduction of decimal base exponents... for example 1000000 can be replaced with 1e6

share|improve this answer
The question asks for tips which are somewhat specific to Javascript. The ternary operator is included in the tips for all languages. – Peter Taylor Mar 17 '14 at 20:36
Yes, but not all languages have the ternary operator, Pete... Besides, I put this in some six months ago... – WallyWest Mar 17 '14 at 22:45
Enough languages have it: there's no point mentioning it on lots of separate per-language tips pages. It's been on the generic tips for some 11.5 months; I've commented on it today because I commented on it in a new language tips page and the person who'd posted it there mentioned that lots of other ones had it. – Peter Taylor Mar 17 '14 at 23:02

When it comes to comparing strings against eachother, you’d normally use


If it is the case that x only has a few fixed options, e.g. x can only be one of the lowercase letters or the asterisk (*), then you can use JavaScript’s string comparison like this:


In the case of limited options, this will be true if and only if x=='*' and false otherwise, saving one amazing byte! This is based on the Unicode table.

For an actual example, see this revision of an answer of mine.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.