Note: Also see Tips for Golfing in ECMAScript 6 and above
@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.
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
whileloop, and then split it into the
a,b,cparts in a
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:
Don't check your types, just use them as they are.
10characters. 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;
Save on brackets by shoving as much as possible into single lines, or parameters:
a( realParam1, realParam2, fizz='buzz' )
a = a - 1;
a = a - 1;
can easily be rewritten as
windowin global context
self explanatory 2 character savings.
Use bracket notation for repeat property access
This is definitely a balancing act between property name length and number of accesses. Instead of calling
a.longFunctionName()with dot notation twice, it's shorter to save the name and call the function via bracket notation:
this is especially effective with functions like
document.getElementByIdwhich can be reduced to
With bracket notation, the cost is
6 + name.lengthcharacters the first time. Each subsequent access has a cost of
For dot notation, all accesses cost
name.length + 1(+1 for the
Use this method if
6 + name.length + (3 * (accesses - 1)) < accesses * (name.length + 1).
len = length of property name
i = minimum accesses to take advantage
len | i
1 | ∞
2 | ∞
3 | 7
4 | 4
5 | 3
6 | 3
7 | 3
8+ | 2
The number of accesses can also span multiple objects. If you access
.length4 or more times on different arrays, you can use the same variable holding the string
`c = ~~a-~~b` should be `c = ~~a+~~b`. Also, you can implicitly cast to integer using `|0`, for example `Math.random()*6|0`.
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.
Where can I add https://github.com/jed/140bytes/wiki/Byte-saving-techniques ?
For "Use Array-Access for repeat function calls" if you're using the function more than twice *on the same object*, what's a bit shorter is to assign the function to a new member like `a.f=a.longfunctionname;a.f(b);a.f(c);a.f(d)`
Again, for loops and the stated while loop equivalent will differ in how they handle `continue` keywords.
@zzzzBov: In code golf, that is usually true, but that's still a point that's worth mentioning.
Instead using `document.getElementById('X').something`, just `X.something` works as well