Whether you’re new to JavaScript or a more seasoned developer it’s always good to learn something new. In this article, we’ll be going over a collection of JavaScript one-liners that hopefully help you tackle some of the daily JavaScript problems that you’ll eventually run into.
Hopefully, you learn a thing or two!
1. Generating a random number within a range
Getting a random value in JavaScript can be easily done with the Math.random() function. But what about a random number in a certain range? There’s no standard JavaScript function for that. The following function can be used to solve this problem.

Note that the max value is included in the range. If you want to exclude the max from the range you can remove the + 1
from the function.
const randomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
2. Toggling a boolean
Toggling a boolean value is one of the oldest tricks in all of the programming books. A very basic programming problem, that can be solved in a lot of different ways. Instead of using if-statements to determine what value to set the boolean to, you could instead use the function below — which is the cleanest way in my opinion.

const toggle = (value) => value = !value
3. Sort the elements of an array in random order
Sorting the elements of an array in random order is can be done by using the Math.random() function. This is a very clean solution to a common problem. However, this way of sorting should not be used to achieve complete randomness. The sort() function should not be used for this. You can find more info about this topic here.

const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)
4. Capitalizing a string
Unlike other popular programming languages like Python, C#, and PHP JavaScript doesn’t have a function that allows you to capitalize a string. However, it’s quite a basic function that gets used a lot. You can put in a word or a complete sentence to this function, as long as it’s a string.

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1)
5. Check if a variable is an array
There are several ways to check if a variable is an array, but this is my preferred way to do it — clean and easy to understand.

const isArray = (arr) => Array.isArray(arr)
6. Extract hostname from URL
Although this one is technically not a one-liner, it’s still a very helpful function. This can be useful for checking if a link is external or internal. Based on that you could add different behavior or styling to certain links.
This function also works with URLs that contain a port number or query string.

const extractHostname = (url) => {
let hostname = (url.indexOf("//") > -1) ? url.split('/')[2] : url.split('/')[0] // Remove port number.
hostname = hostname.split(':')[0] // Remove querystring.
hostname = hostname.split('?')[0] return hostname
}
7. Get the unique values in an array
A very simple, yet super neat trick to remove all duplicate values from an array. This trick converts the array that we use as the first parameter to a Set and then back to an array.

const uniqueValues = (arr) => [...new Set(arr)]
8. Checking whether all items in an array meet a certain condition
The every method checks whether all the items in an array meet a certain condition. This method takes a callback as its only parameter and returns a boolean.
Tip: if you only need one element in an array to meet a certain condition, you can use the some() method.

const isOldEnough = (age) => age >= 18
const ages = [7, 19, 12, 33, 15, 49]ages.every(isOldEnough) // Results in falseconst olderPeople = [39, 51, 33, 65, 49]olderPeople.every(isOldEnough) // Results in true
9. Formatting floats based on locale
Formatting floats can be done in several ways. However, if you’re working on an application that supports multiple locales the format might differ. The following one-liner supports formatting float for different locales.
Tip: if you need to support multiple locales you can add a third parameter to this function for the locale.

const formatFloat = (floatValue, decimals) => parseFloat(floatValue.toFixed(decimals)).toLocaleString("en-US")
10. Updating the query string
Updating the query string can be extremely helpful when working with filters, for example. Here’s an example of how you can update the query string with JavaScript’s URLSearchParams interface.

const searchParams = new URLSearchParams(window.location.search)searchParams.set('key', 'value')history.replaceState(null, null, '?' + searchParams.toString())
Note that the window.location.search that’s passed to the URLSearchParams will keep the current query string intact. This means that, in this example, the key=value will be added to the current query string. If you want to build a query string from scratch, leave out the window.location.search parameter.
11. Only positive numbers allowed
There will be times where you want a variable to only contain positive numbers. Instead of having to use if-statements to check whether the number is negative, you can use the following one-liner:

const getPositiveNumber = (number) => Math.max(number, 0)
This one-liner can be used instead of a code snippet that looks like this:

The Math.max() solution is much cleaner, right?
12. Show the print dialog
The following line of code will show the print dialog which can be helpful if you want to provide a user-friendly way for the user to print a certain page on your website.
const showPrintDialog = () => window.print()
13. Copy text to clipboard
Copying text to the clipboard is a problem that can be solved in various ways.
If you only care about supporting modern browsers, the following example would be sufficient:

const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text)
}
This is a pretty clean solution that doesn’t rely on any DOM elements.
Note that this function is asynchronous since the writeText function returns a Promise.
However, if you want to support older browsers like Internet Explorer you’ll have to take this approach:


This solution relies on an input field as opposed to the previous, Promise based, solution.
// HTML<input id="input" type="text" value="This is the text that gets copied">
<button id="copy">Copy the text</button>// JavaScriptconst copy = () => {
const copyText = document.querySelector('#input')
copyText.select()
document.execCommand('copy')
}
document.querySelector('#copy').addEventListener('click', copy)
14. Casting all values in an array
We can use the map function on an array to cast all of its items to a certain type. In the example, you’ll see that we first cast an array of string to an array of numbers. After that, we convert the number array to booleans.

const arrayToNumbers = (arr) => arr.map(Number)
const numbers = arrayToNumbers(['0', '1', '2', '3'])const arrayToBooleans = (arr) => arr.map(Boolean)
const booleans = arrayToBooleans(numbers)
15. Calculate the number of days between two dates
Calculating the number of days between two dates is one of these things that you’ll probably do more than once if you’re programming in JavaScript a lot. To save you the hassle of figuring out how this problem can be solved every single time you can use this function that does the hard work for you.
Due to the use of Math.abs() the order of the date arguments is irrelevant.

const daysBetweenDates = (dateA, dateB) => {
const timeDifference = Math.abs(dateA.getTime() - dateB.getTime())
// Seconds * hours * miliseconds
return Math.floor(timeDifference / (3600 * 24 * 1000))
}daysBetweenDates(new Date('2020/10/21'), new Date('2020/10/29'))
// Result: 8daysBetweenDates(new Date('2020/10/21'), new Date('2021/10/29'))
// Result: 373
That’s it!
Now that you’ve reached the end of this list I hope that you learned a couple of new things. Hopefully, you can put a few of these tricks into practice. If you know a great JavaScript one-liner that’s not on this list, please let me know. I’d love to see some more great one-liners.
Thanks for reading!
Comments
Post a Comment