27 Essential One-Line JavaScript Functions Used By Developers Daily
In this article, I have compiled a list of 27 one-line JavaScript Functions that are used daily and needed by every developer. It doesn’t matter if you are a beginner, intermediate, or pro JavaScript developer. At some point, you use these functions, either in your daily work or in your personal projects. If you write code on a daily basis, I guarantee that you always have a need to use these functions. I read a lot of online resources and compiled the most useful one-line JavaScript functions.
Let’s Start
1. Copy to Clipboard
A useful one-line JavaScript function, which can be used to easily copy any text to the clipboard.
2. Get a random number in a specific range
An essential JavaScript function to generate a random number between a specific range of numbers. You provide a minimum and a maximum value as arguments and the one-line function returns a random number from the given range.
3. Convert RGB to Hex
A useful function on this list, which is used to convert the RGB to hex code.
4. Scroll to Page Top
Another useful JavaScript function in this list, which is used to automatically scroll to the top of the web page.
5. Find the number of gap days between two dates
The next function is a very useful one-liner when you are working with Calendar/Dates in JavaScript. Find the gap days between 2 given dates using the following code.
6. Generate Random Hex
You can generate random hex colors using this function, which is very useful for frontend projects.
7. Check if the provided day is a weekday
Using this function, you will be able to check if the date that you pass as the argument, is either a weekday or weekend day.
8. Convert Temperature Fahrenheit / Celsius
If you are dealing with temperature in your project then these 2 are very helpful JavaScript functions. These 2 functions will help you convert Fahrenheit to Celsius and vice-versa.
9. Check if the user is on an Apple device
As in a lot of projects, we need to implement device-based features. You can use this function to make sure that the user is using an Apple device or not.
10. Get the time from a date
You can use the .toTimeString() method and by slicing the string at the correct place, we can get the time from a date that we provide, or get the current time.
11. Strip HTML From Text
A very handy JavaScript one-line function which is also important for security reasons. Users can submit the tag-based input values. When accepting user inputs, you can strip any HTML elements in the text user entered with the help of DOMParser.
12. Toggle (show/hide) of an Element
You can easily toggle between show/hide an element with this single line method, using the CSS display property value.
13. Reverse a String
You can reverse a string in one line using split
, join
, and reverse
methods.
14. Capitalize a String
As JavaScript doesn’t provide a built-in capitalize method, using this one-line function you can capitalize a string.
15. Round Decimals to a Certain Number of Decimal Places
When you are dealing with amounts, calculations in decimals are very important and should be very precise and reliable. To use the Rounding decimals to a fixed number of decimal points is a tricky business in JavaScript. The built-in JavaScript toFixed() method can easily do this conversion, but it gives weird results in several cases because of the way floating-point arithmetics work.
To avoid this strange behavior, you can represent the numbers in exponential notation and use Math.round() to get the decimal rounded to a given number of decimal places.
16. Shuffle an Array
You can use the following code to shuffle an array. It uses sort
and random
methods.
17. Detect Dark Mode
Find out if a user’s device is in dark mode, using the following code.
18. Get Query Params from URL
Very useful function when you are dealing with url, query parameters. You can easily retrieve query parameters from a url by passing, url as the argument of the function.
19. Get the Average of an Array of Number
JavaScript reducer allows calculating the average of a number of arrays in a single line. Reduce method is quite useful when writing one-line solutions to a number of problems like finding the sum or maximum in an array of numbers.
20. Check if the current user has touch events supported
21. Find the day of the year
Another very useful JavaScript function relevant to Dates/Calendar. It basically provides you with the day count of the year. For example, 6th February has a count of 37 out of 365 days in a year.
22. Get Value of a browser Cookie
A useful short function of JavaScript meant to get the value of a browser cookie.
23. Clear All browser Cookies
Another one-liner relevant to cookies which can be used to easily clear all cookies stored in a web page by accessing the cookie using document.cookie
and clearing it.
24. Get a random boolean value (true/false)
This function will return a boolean (true or false) using the Math.random()
method. Math.random
will create a random number between 0 and 1, after which we check if it is higher or lower than 0.5. That means it’s a 50/50 chance to get either true or false.
25. Remove Duplicates in an Array
sets in JavaScript only store unique items. We can use this behavior to remove duplicate items from an array. However, it only works with arrays storing primitive data. So you’d have to write a multiline solution to remove duplicates in arrays storing objects. But, still, it’s a quite decent method to remove duplicates in simple scenarios.
26. Check if Date is Valid
Check the user date input validity, using this Js function.
27. Get a random item from an array
This one-liner returns you a random item from your input array, that you pass as an argument to the function.
Conclusion:
If you have ideas to extend this list, please feel free to mention your ideas in the comments. I would love to extend this list with your suggestions. If you like the article and want to see more content in the future, then don’t forget to follow me on Medium. Happy coding!
About the author:
I work as a full-stack developer at Lucid.Studio and I’m very interested to learn and share my knowledge with the community. If you liked my work, then connect with me on LinkedIn: Sayyed Hammad Ali.
Other articles you might Like:
Credits to Sources:
- https://modernweb.com/45-javascript-tips-tricks-practices/
- https://dev.to/saviomartin/20-killer-javascript-one-liners-94f
- https://www.thatsanegg.com/blog/13-javascript-one-liners-that%E2%80%99ll-make-you-look-like-a-pro/
- https://livecodestream.dev/post/awesome-javascript-one-liners-to-look-like-a-pro/
More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.