Code-golf techniques, part 2

Barely related photo by AK¥N Cakiner on Unsplash

See previous article for literals and variables. Disclaimer is also there.

Expressions

  • If all parts of your expression resolve to boolean values or non-negative numbers, you can replace && and || with * and +:
// Long:
d=a&&b||c
// Short:
d=a*b+c
  • String concatenation can be replaced with interpolation:
// Long:
s='prefix'+a+'infix'+b+'suffix'
// Short:
s=`prefix${a}infix{$b}suffix`
  • Works even better with more complex expressions as interpolation implies parenthesis:
// Long:
s='prefix'+(a+b)+'suffix'
// Short:
s=`prefix${a+b}suffix`
  • Making comparisons strict saves a character:
// Long:
for(i=1;i<=50;i++)
// Shorter:
for(i=1;i<51;i++)
  • And rearranging code (if possible) to change static comparison part to zero can make it even shorter:
// Shorter:
for(i=1;i<51;i++)
// Shortest:
for(i=51;i;i--)

Conversions

  • Integer part of number:
// Long:
Math.floor(n)
// Short:
~~n
  • String to number (base 10):
// Long:
parseInt(s)
// Short:
+s
  • Kinda of obvious, but still; number to string (base 10):
// Long:
n.toString(10)
// Short:
''+n
  • Number to string (base 2):
// Just conversion:
n.toString(2)
// If fixed width is worth additional characters:
n.toString(2).padStart(8,0)
  • String to array of characters:
// Long:
a=s.split('')
// Short:
a=[...s]

Loops

  • Generally standard for is pretty good, just don’t forget you can use comma to put several operations in either section:
for(a=1;a<10;a++)
for(a=1,s='',o=[];a<10,s+=a;o.unshift(s),a++)
  • Sometimes recursive function with exit condition is better, but this generally happens if you can reuse the function several times:
(g=(n,f)=>n?(f(n),g(--n,f)):0)(10,print)
  • There are cases when loop can be implemented via regular expressions, but again, this really depends on case specifics:
print('123456789'.replace(/./g,c=>c*c+' '))
  • Don’t forget about Array.prototype.map, specifically works good with arguments:
arguments.map(a=>print(a))
  • Sometimes loop is not needed at all, as it is shorter to ‘compile’ JavaScript expression as a string and then evaluate it, e.g. look at this code that calculates sum of digits:
n=12345// Long:
for(s=0,a=n;a;a/=10)s+=~~a%10
// Short:
eval([...''+n].join('+'))

That’s it for now.