J

10 JavaScript One-Liners That Will Save You Hours of Coding

PinoyFreeCoder
Fri Nov 22 2024
PinoyFreeCoder
Fri Nov 22 2024

10 JavaScript One-Liners That Will Save You Hours of Coding

JavaScript is a versatile language that often allows developers to solve problems concisely. In this article, we explore 10 powerful JavaScript one-liners that can save you time and effort. These snippets showcase the language's flexibility, making your code cleaner and more efficient.

1. Clone an Array

Quickly clone an array using the spread operator:


      const clonedArray = [...originalArray];
      

2. Check for Palindromes

Determine if a string is a palindrome:


      const isPalindrome = str => str === str.split('').reverse().join('');
      

3. Flatten an Array

Flatten a nested array to a single level:


      const flattened = arr.flat(Infinity);
      

4. Generate a Random Hex Color

Quickly generate a random hex color code:


      const randomHexColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
      

5. Remove Duplicates from an Array

Remove duplicate elements in an array:


      const uniqueArray = [...new Set(array)];
      

6. Swap Two Variables

Swap two variables without a temporary variable:


      [a, b] = [b, a];
      

7. Find the Maximum Value in an Array

Find the largest number in an array:


      const max = Math.max(...array);
      

8. Convert a String to a Number

Convert a string to a number using the unary + operator:


      const num = +str;
      

9. Shuffle an Array

Randomize the order of elements in an array:


      const shuffled = array.sort(() => Math.random() - 0.5);
      

10. Convert an Object to Query String

Convert an object to a URL query string:


      const queryString = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');
      

Conclusion

These one-liners demonstrate the simplicity and power of JavaScript. By incorporating them into your workflow, you can write cleaner, more concise code while saving time. Which of these one-liners is your favorite? Let us know in the comments!

Start Your Online Store with Shopify

Build your e-commerce business with the world's leading platform. Get started today and join millions of successful online stores.

🎉 3 MONTHS FREE for New Users! 🎉
Get Started
shopify