J

10 JavaScript One-Liners to Simplify Your Code

PinoyFreeCoder
Sun Nov 24 2024
PinoyFreeCoder
Sun Nov 24 2024

10 JavaScript One-Liners to Simplify Your Code

JavaScript is a powerful and versatile language, ideal for modern web development. In this article, we explore 10 concise JavaScript one-liners that can make your code cleaner and more efficient. Whether you're working on frontend or backend projects, these snippets will help streamline your workflow.

1. Check if a Number is Even


      const isEven = num => num % 2 === 0;
      console.log(isEven(4)); // Output: true
      

2. Generate a Random Number in a Range


      const randomInRange = (min, max) => Math.random() * (max - min) + min;
      console.log(randomInRange(1, 10)); // Output: a random number between 1 and 10
      

3. Reverse a String


      const reverseString = str => str.split('').reverse().join('');
      console.log(reverseString('hello')); // Output: 'olleh'
      

4. Flatten an Array


      const flattenArray = arr => arr.flat(Infinity);
      console.log(flattenArray([[1, 2], [3, [4, 5]]])); // Output: [1, 2, 3, 4, 5]
      

5. Remove Duplicates from an Array


      const uniqueArray = arr => [...new Set(arr)];
      console.log(uniqueArray([1, 2, 2, 3])); // Output: [1, 2, 3]
      

6. Get the Current Date in YYYY-MM-DD


      const currentDate = new Date().toISOString().split('T')[0];
      console.log(currentDate); // Output: '2024-11-24' (varies by current date)
      

7. Capitalize the First Letter of a String


      const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
      console.log(capitalize('javascript')); // Output: 'Javascript'
      

8. Check if an Object is Empty


      const isEmpty = obj => Object.keys(obj).length === 0;
      console.log(isEmpty({})); // Output: true
      

9. Sort an Array of Numbers


      const sortedArray = arr => arr.sort((a, b) => a - b);
      console.log(sortedArray([3, 1, 4, 2])); // Output: [1, 2, 3, 4]
      

10. Get the Intersection of Two Arrays


      const intersect = (arr1, arr2) => arr1.filter(item => arr2.includes(item));
      console.log(intersect([1, 2, 3], [2, 3, 4])); // Output: [2, 3]
      

Conclusion

These JavaScript one-liners highlight the elegance and functionality of the language. By mastering these snippets, you can write cleaner and more efficient code. Do you have a favorite JavaScript one-liner? Share it in the comments!