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. [GFGTABS] JavaScript function sum(x, y) { return x + y; } console.log(sum(6, 9)); [/GFGTABS]Output1
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 Indexed Collections
Indexed collections in JavaScript refer to data structures like arrays, where elements are stored and accessed by numerical indices. Arrays allow for efficient storage and retrieval of ordered data, providing methods for manipulation and traversal of their elements. Example an array called 'student'
5 min read
JavaScript eval() Function
The eval() function in JavaScript is a powerful but potentially dangerous feature that allows the execution of JavaScript code stored in a string. While eval() can be useful in some cases, its use is generally discouraged due to security risks and performance concerns. Executing JavaScript Code with
3 min read
Creating objects in JavaScript
An object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, e
5 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 (//), [GFGTABS] JavaScript // A single line
2 min read
Abstraction in JavaScript
In JavaScript, Abstraction can be defined as the concept of hiding the inner complex workings of an object and exposing only the essential features to the user. Hiding Complexity: Implementation is hidden, it shows only the necessary details.Modularity: Code is organized in a reusable form, which im
4 min read
Interesting Code Snippets in JavaScript
JavaScript is a flexible and powerful programming language that can solve problems in clever and simple ways. Here are some fun JavaScript code snippets that highlight its features and quirks. Whether you're a beginner or an experienced developer, these examples will spark your interest. 1. Flatteni
5 min read