Code Golfing in JavaScript
Last Updated :
29 Jan, 2020
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.
2. Checking the case of literals: We can even compare the literal with
{} for checking its case, it returns
true for the uppercase and
false for the lowercase.
3. Floor the value: A straight forward solution is used in floor function present in the Math library but it takes little more characters. We can do the same in a few characters by using the
| operator.
- Original Code:
a = Math.floor(a);
- Golfed Code:
a = 0 | a;
4. Ceil value: A straight forward solution is to use ceil function present in the Math library but it takes little more characters. We can do the same in a few characters by using the combination of
%, ~ operator.
- Original Code:
a = Math.ceil(a);
- Golfed Code:
a = a%1 ? -~a : a;
5. Rounding the value: A straight forward solution is used to round function present in the Math library but it takes little more characters. We can do the same in a few characters by using the combination of
|, + operator.
- Original Code:
a = Math.round(a);
- Golfed Code:
a = 0 | a + .5;
6. Arrow functions: Arrow functions provides a concise way to write functions in the JavaScript.
7. Alternatives for min function: Ternary operator always saves bytes. We can compare two numbers using the ternary operator.
- Original Code:
Math.min(x, y);
- Golfed Code:
a < b ? a : b
8. Alternatives for max function: Ternary operator always saves bytes. We can compare two numbers using the ternary operator.
- Original Code:
Math.max(x, y);
- Golfed Code:
a < b ? b : a
9. Absolute value: A straight forward solution is to use absolute function present in the Math library but it takes little more characters. We can do the same in a few characters by using the ternary operator.
- Original Code:
Math.abs(x)
- Golfed Code:
x < 0 ? -x : x
10. Save bytes in Loops: We can save bytes by changing the variable on the last time used.
11. Calculating Sum or Product of Array: We have the option to do task by iterating the loop but for saving bytes we can use
eval and arithmetic operators like
+, *, ^etc.
12. Check for NaN: NaN method in JavaScript is used to determines whether the passed value is NaN(Not a Number) and is of the type “Number”.
Note: It only works if typeof(x) == "number"
13. for vs while loops: Both loops are efficient in terms of time complexity but when it comes to space complexity, many times
for loop outbeats
while loop.
14. Combining Nested loops into a single loop: We can combine the nested loop of 2 or more degree into a single 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)
15. Generating Random numbers between the range: We can use the Date class to generate the random number because the Date is stored internally in JavaScript as the number of milliseconds since an epoch.
Similar Reads
Debugging in JavaScript Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs. It involves:Identifying errors (syntax, runtime, or logical errors).Using debugging tools to analyze code execution.Implementing fixes and verifying correctness.Types of Errors in JavaScriptSyntax Errors:
4 min read
JavaScript Code Execution JavaScript is a synchronous (Moves to the next line only when the execution of the current line is completed) and single-threaded (Executes one command at a time in a specific order one after another serially) language. To know behind the scene of how JavaScript code gets executed internally, we hav
4 min read
Functions in JavaScript Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
5 min read
JavaScript if-else JavaScript if-else statement executes a block of code based on a condition. If the condition evaluates to true, the code inside the "if" block executes; otherwise, the code inside the "else" block, if present, executes. Such control statements are used to cause the flow of execution to advance and b
4 min read
JavaScript Comments Comments help explain code (they are not executed and hence do not have any logic implementation). We can also use them to temporarily disable parts of your code.1. Single Line CommentsA single-line comment in JavaScript is denoted by two forward slashes (//), JavaScript// A single line comment cons
2 min read