Skip to main content

15 Helpful JavaScript One-Liners

 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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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:

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.

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:

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.

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.

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.

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

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...