Code Golfing in JavaScript
Last Updated :
29 Jan, 2020
Improve
Code Golf in JavaScript refers to attempting a problem to solve using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters "wins". JavaScript is a fantastic language for code golfing due to backward compatibility, quirks, it is being a high-level language, and all the coercion. So, here we will look at some Code Golfing techniques in JavaScript language:
1. Checks if a variable is equal to some positive no: We can simply do this with a bunch of if-else statements, but we have different methods also like subtracting that positive integer from the number and checks whether it is greater than zero or not.

- Original Code:
if(a == 5){ yes(); }else{ no(); }
- Golfed Code - I
x == 3 ? "y" : "n";
- Golfed Code - II
x-3 ? "y" : "n";
- Golfed Code - III
x^3 ? "y" : "n";
- Golfed Code:
'g' < {} // Returns false, lower case 'G' < {} // Returns true, upper case
- Original Code:
a = Math.floor(a);
- Golfed Code:
a = 0 | a;
- Original Code:
a = Math.ceil(a);
- Golfed Code:
a = a%1 ? -~a : a;
- Original Code:
a = Math.round(a);
- Golfed Code:
a = 0 | a + .5;
- Original Code:
g = function (a) { return a * a * a; }
- Golfed Code:
g = a => a*a*a;
- Original Code:
Math.min(x, y);
- Golfed Code:
a < b ? a : b
- Original Code:
Math.max(x, y);
- Golfed Code:
a < b ? b : a
- Original Code:
Math.abs(x)
- Golfed Code:
x < 0 ? -x : x
- Original Code:
for(x = 0; x < 10; x++){ alert(x); }
- Golfed Code:
for(x = 0; x < 3 ; ){ alert(x++); }
- Golfed Code:
eval(a.join('+')) eval(a.join`+`) eval(a.join('*')) eval(a.join`*`)
- Original Code:
if(isNaN(x)){ alert(x); }
- Golfed Code:
if(x != x){ alert(x); }
- Golfed Code:
i = 10; while(i--); # While loop for(i = 10; i--; ); # For loop
- Original Code:
for(i = 10; i--; ) for(j = 5; j--; ) do_something(i, j)
- Golfed Code:
for(i = 50; i--; ) do_something(0 | i/5, i%5)
- Golfed Code:
new Date%1500 // Random integer 0 <= x < 1500