JavaScript is full of hidden gems. Many times, we end up writing long functions for tasks that can actually be solved in just a single line of code.
Here are 10 clever JavaScript one-liners that can simplify your code and speed up your workflow.
1. Reverse a String
Split the string into an array, reverse it, and join it back together.
2. Check if a String is a Palindrome
Compares the string with its reversed version.
3. Get a Random Number Between Two Values
Generates a random integer between min and max.
4. Shuffle an Array
Uses the array sort() method with a random comparator.
5. Get Unique Values from an Array
Set automatically removes duplicates.
6. Flatten a Nested Array
The flat() method with Infinity flattens arrays of any depth.
7. Capitalize the First Letter of a String
Quick way to make titles and labels look nice.
8. Get Query Parameters from a URL
Turns query parameters into a clean object.
9. Check if a Number is Even
Simple modulus check — quick and clean.
10. Generate a Random Hex Color
Handy for generating random colors for backgrounds or UI elements.
🎯 Conclusion
These one-liners show how powerful and concise JavaScript can be. Instead of writing 5–10 lines, you can often solve problems in just one line.
👉 Which one was your favorite? Do you know other cool one-liners?
Drop them in the comments — let’s build a collection together!
If you found this useful, follow me for more JavaScript, React, and Next.js tips 🚀
Top comments (0)