Friday, November 15, 2024
Google search engine
HomeLanguagesJavascriptCode Golfing in JavaScript

Code Golfing in JavaScript

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";
    

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.

  • Golfed Code:
    'g' < {}     // Returns false, lower case
    'G' < {}     // Returns true, upper case
    

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.

  • Original Code:
    g = function (a) {
       return a * a * a;
    }
    
  • Golfed Code:
    g = a => a*a*a;
    

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.

  • Original Code:
    for(x = 0; x < 10; x++){
      alert(x);
    }
    
  • Golfed Code:
    for(x = 0; x < 3 ; ){
      alert(x++);
    }
    

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.

  • Golfed Code:
    eval(a.join('+'))
    eval(a.join`+`)
    
    eval(a.join('*'))
    eval(a.join`*`)
    

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”.

  • Original Code:
    if(isNaN(x)){
        alert(x);
    }
    
  • Golfed Code:
    if(x != x){
        alert(x);
    }
    

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.

  • Golfed Code:
    i = 10;
    while(i--);    # While loop
    
    for(i = 10; i--; );     # For 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.

  • Golfed Code:
    new Date%1500   // Random integer 0 <= x < 1500
    
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments