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). Please post one tip per answer.
Fancy For Loopsyou can use the standard for loop in non-standard ways
is essentially equivalent to:
so a good trick is to write your code with a A couple examples I've written:
Chain your settersIf you're initializing or resetting multiple values, chain the value to all the variables that need it:
Implicit CastingDon't check your types, just use them as they are.
Avoid SemicolonsJavaScript has automatic semi-colon insertion. Use it often and well. One-linersSave on brackets by shoving as much as possible into single lines, or parameters:
Increment/Decrement operators
and
can easily be rewritten as
and
respectively. Use
|
|
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 |
||
|
You can use the object literal form of get/set to avoid using the keyword
|
||||
|
|
Taking advantage of short-circuit operatorsRather than long
can become
The
This is the same as writing
Creating repetitive strings using ArrayIf 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:
The larger the string, the bigger the saving. Parsing numbersUse
Be wary though, other types can be coalesced with these operators (for instance, |
|||||
|
|
Use the comma operator to avoid braces (also applies to C):
Instead of
which is one character longer. |
||||
|
Use a bitwise operation to round a number toward zero:
(Source: Random dice tipping) Operator precedence determines which will be shorter in your program. |
|||||||||||||
|
|
Use Mozilla's proprietary "expression closure" feature to save many characters in a script that only needs to work in the SpiderMonkey/Firefox or Rhino engines. For example,
becomes
See the Stack Overflow page for more such tricks. |
|||||
|
|
|
Converting a
But the second form can have variable initialization combined:
Notice the second form is one character shorter than the first form. |
||||
|
|
|
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:
You might normally shorten this function using a single-letter variable name:
A better way to reduce the length is by abusing
|
||||
|
|
|
Sneak variable initialization into the prompt() call for getting user input
instead of using
As a side-effect, it displays the input value in the prompt window while saving 1 character. |
|||||||||||||
|
|
Initialize arrays with
|
|||||
|
|
for a given array, we know a So instead of this iteration:
lets do this:
if we just want to iterate the Array not caring it goes backwards |
|||||||||||||
|
|
Another thing I came across is forcing a multidimensional array into a single-dimensional array like this:
It does convert everything into strings, so basically only numbers/strings are possible, but it can come in handy. Calculating with strings automatically converts it into numbers anyway. EDIT: As Austin Hyde pointed out, you can flatten one level like this:
Although it only takes it down one level, the data types remain. |
|||||||||||||||
|
|
In some cases, a conditional check for empty can be replaced with multiplication. For instance:
Returns 42 if a is 1 and 0 if a is 0. This does the same thing:
and saves two characters. |
|||||||
|
|
If you're initializing a variable to
Since the result of a condition like
You can usually save 2 characters using this method. Regards to For another example, I also applied this trick to my answer here with the expression |
||||
|
|
|
Transforming to a Boolan:
Note: They change |
||||
|
|
|
combine nested for loops
|
||||
|
|
Sometimes declaring a variable (or more) as function parameters can save some strokes by avoiding the
Also you can use short circuit operators to avoid if statements:
To coerce to a number: |
||||
|
|
|
You can check if a value is *truish by simply passing it:
This method can be applied with many other functions and operators:
Note: it is exactly to |
||||
|
|
|
Repeated characters Be creative when trying to repeat the same character:
Note: It is unlikely that you use it to form a string, but the idea can be applied to form large numbers too |
|||||||
|
|
Treat strings like you do C Strings. Given
is equivalent to
and
|
||||
|
|
|
Less/Greater than "10/100/1000..." vs "9/99/999...":
Note: Just remember to swap what is inside the |
||||
|
|
|
Adding Values with Implicit Casting Improved zzzzBov solution:
We save Note: you MUST leave the space between the |
|||||
|
|
Looping Tip I You can save
Note: works with 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 |
||||
|
|
|
Splitting with numbers to save the quotemarks:
|
||||
|
|
|
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
And in case you are wanting to compare with a negative number (*different than *well, you can surely use |
||||
|
|
|
Some extra tricks that I don't see very often, that are more JS-specific:
|
||||
|
|
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