DEV Community

Cover image for Master JavaScript: 18 One-Liners to Elevate Your Code
chintanonweb
chintanonweb

Posted on

Master JavaScript: 18 One-Liners to Elevate Your Code

Effortless JavaScript: 18 Genius One-Liners for Productivity

Introduction

JavaScript is a versatile programming language known for its flexibility and ease of use. As a developer, mastering concise and elegant solutions can greatly enhance your productivity and efficiency. One-liners, in particular, are snippets of code that achieve significant functionality in just a single line. In this article, we'll explore 18 JavaScript one-liners that will not only streamline your code but also showcase your expertise to colleagues and potential employers.

1. Flatten an Array

const flattenedArray = arrayToFlatten.reduce((acc, val) => acc.concat(val), []);
Enter fullscreen mode Exit fullscreen mode

Flattening nested arrays is a common task in JavaScript. This one-liner utilizes the reduce() method to concatenate each element of the nested arrays into a single flattened array.

2. Check if Array Contains Duplicates

const hasDuplicates = arr => new Set(arr).size !== arr.length;
Enter fullscreen mode Exit fullscreen mode

By converting the array to a Set, duplicates are automatically removed. Then, we compare the size of the Set to the original array length to determine if duplicates exist.

3. Convert String to Title Case

const toTitleCase = str => str.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
Enter fullscreen mode Exit fullscreen mode

This one-liner converts a string to title case by first converting it to lowercase and then using a regular expression to capitalize the first letter of each word.

4. Shuffle an Array

const shuffledArray = arrayToShuffle.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

Shuffling an array randomly reorders its elements. Here, we use the sort() method with a random comparator function to achieve this in just one line.

5. Find Maximum Value in an Array

const maxNumber = Math.max(...arrayOfNumbers);
Enter fullscreen mode Exit fullscreen mode

The spread operator (...) is used to pass the elements of the array as arguments to the Math.max() function, returning the maximum value.

6. Check if Object is Empty

const isEmptyObject = obj => Object.keys(obj).length === 0;
Enter fullscreen mode Exit fullscreen mode

By retrieving the keys of the object and checking their length, we can determine if the object is empty in a single line.

7. Remove Falsy Values from an Array

const truthyValues = array.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

The filter() method is used with the Boolean constructor as the callback function, effectively removing falsy values (e.g., false, 0, "", null, undefined, and NaN) from the array.

8. Generate a Random Hex Color Code

const randomHexColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
Enter fullscreen mode Exit fullscreen mode

This one-liner generates a random hexadecimal color code by leveraging Math.random() and toString(16) to convert the randomly generated number to hexadecimal format.

9. Capitalize the First Letter of a String

const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
Enter fullscreen mode Exit fullscreen mode

By extracting the first character of the string and capitalizing it, we achieve the desired effect of capitalizing the first letter.

10. Swap the Values of Two Variables

[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

This elegant one-liner uses array destructuring to swap the values of a and b without needing a temporary variable.

11. Check if a String Contains a Substring

const containsSubstring = (str, substr) => str.includes(substr);
Enter fullscreen mode Exit fullscreen mode

The includes() method is used to check if the given string contains the specified substring, returning true or false accordingly.

12. Reverse a String

const reversedString = str.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

By splitting the string into an array of characters, reversing the array, and then joining it back into a string, we effectively reverse the original string.

13. Calculate the Factorial of a Number

const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
Enter fullscreen mode Exit fullscreen mode

This concise recursive function calculates the factorial of a given number, demonstrating the power of one-liners in solving mathematical problems.

14. Group Array Elements by a Property

const groupBy = (arr, key) => arr.reduce((acc, obj) => ({ ...acc, [obj[key]]: (acc[obj[key]] || []).concat(obj) }), {});
Enter fullscreen mode Exit fullscreen mode

Using reduce(), this one-liner groups array elements by a specified key, creating an object where keys correspond to distinct values of the specified property.

15. Convert Fahrenheit to Celsius

const fahrenheitToCelsius = fahrenheit => (fahrenheit - 32) * 5 / 9;
Enter fullscreen mode Exit fullscreen mode

This simple formula converts temperature from Fahrenheit to Celsius in just one line, showcasing the elegance of JavaScript arithmetic operations.

16. Truncate a String

const truncateString = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
Enter fullscreen mode Exit fullscreen mode

By checking if the string length exceeds the maximum length, this one-liner truncates the string and adds ellipsis if necessary, making it suitable for display purposes.

17. Calculate the Sum of Array Elements

const sumArray = arr => arr.reduce((acc, val) => acc + val, 0);
Enter fullscreen mode Exit fullscreen mode

Utilizing the reduce() method, this one-liner computes the sum of all elements in an array, providing a succinct solution to a common task.

18. Check if a Number is Prime

const isPrime = num => {
    for(let i = 2, sqrt = Math.sqrt(num); i <= sqrt; i++)
        if(num % i === 0) return false;
    return num > 1;
};
Enter fullscreen mode Exit fullscreen mode

This compact function efficiently determines whether a given number is prime by iterating up to the square root of the number and checking for divisibility.

FAQs

What are JavaScript one-liners?

JavaScript one-liners are concise snippets of code that achieve significant functionality in just a single line. They are often used to streamline code and showcase programming expertise.

Are one-liners always recommended in JavaScript programming?

While one-liners can be efficient and elegant, they may sacrifice readability in some cases. It's essential to strike a balance between brevity and clarity, considering the context and maintainability of the code.

Can I use these one-liners in my projects?

Absolutely! These JavaScript one-liners demonstrate various useful techniques and can be incorporated into your projects to enhance productivity and code quality.

How can I improve my skills in writing JavaScript one-liners?

Practice is key to mastering JavaScript one-liners. Experiment with different approaches, study existing code, and continuously challenge yourself to find more concise and elegant solutions to common programming tasks.

Conclusion

Mastering JavaScript one-liners can significantly enhance your programming skills and efficiency. By leveraging these concise and elegant solutions, you can streamline your code, impress your peers, and tackle complex problems with ease. Keep exploring, practicing, and refining your skills to become a JavaScript

Top comments (0)