• 11 Rare JavaScript one-liners That Will Amaze You
  • Can Durmus
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: jaredliw
  • Proofread by: Z Zhaojin, KimYangOfCat

11 rare single lines of JavaScript that will wow you

If you wanted to impress professional developers, what would you do? It’s simple: solve a complex problem with a simple strategy and as little code as possible. With the introduction of arrow functions in ES6, we can create single lines of code that look elegant and simple.

In this article, you’ll learn about 11 rare but powerful single lines of code. So, get ready, let’s start with the first one!

1. Obtain the number of characters in the string

Getting the number of characters is a very useful feature that can be used in many scenarios. You can use it to get the number of Spaces and subsequent words, or to get the count of a delimiter in a string.

const characterCount = (str, char) = > str.split(char).length - 1
Copy the code

The idea is very simple. We split the string using the passed argument char and get the length of the returned array. Each time the string is split, the result is one more than the separator. Subtract 1 and we have a single line of characterCount.

2. Check whether the object is empty

Checking whether an object is empty is actually more difficult than you might think. Even if the object is empty, each check to see if the object is equal to {} returns false.

Fortunately, the following single line of code does what we want to do.

const isEmpty = obj= > Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
Copy the code

In this line, we check whether the length of the object’s key is equal to zero and whether the argument passed is an object.

3. Wait a certain period of time before executing the command

In this single line of code, we’ll touch on some simple asynchronous programming concepts. If you want to wait a certain amount of time while running code, this is a single line of code to wait:

const wait = async (milliseconds) => new Promise((resolve) = > setTimeout(resolve, milliseconds));
Copy the code

In the single line of wait, we create a Promise object and use the setTimeout function to complete it after a given time.

4. Obtain the difference between two dates

Dates are often the most confusing part of Web application development, because there are so many concepts that can lead to miscalculations.

This is a powerful single line of code to calculate the difference in days between two dates. But that’s not the end of it. Like me, you can create your own one-line code to calculate the difference in months, years, and so on.

const daysBetween = (date1, date2) = > Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))
Copy the code

The logic behind this single line of code is easy to understand. When two dates are subtracted, the difference is returned in milliseconds. To convert milliseconds into days, we must divide it by milliseconds, seconds, minutes, and hours.

5. Redirect to another URL

If you’ve ever created a real website, I’m sure you’ve encountered authentication logic. For example, non-administrator users should not be able to access the /admin route. If the user tries to access it, then you have to redirect it to another URL.

This single line of code works just fine for the situation I mentioned above, but I think you can find more usage scenarios.

const redirect = url= > location.href = url
Copy the code

Location is a method in the global Window object that sets the href property to behave the same as when the user clicks a link.

6. Check whether the device supports touch screen

As the number of devices that can connect to the Internet grows, so does the need to create responsive websites. Twenty years ago, developers should have considered desktop websites, but today more than 50% of web traffic comes from touch devices. So it’s important to take some action to support touch screens on devices.

const touchSupported = () = > ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)
Copy the code

In this line, we are checking to see if document supports the TouchStart event.

7. Insert a string of HTML after the element

It is common to update the DOM with JavaScript when developing Web applications. There are some basic methods built into JavaScript that can do this, but when things get complicated, things can become difficult to overcome.

This is a single line of code that injects a string of HTML immediately after the HTML element. With a few minutes of thought and a Google search, I’m sure you can find the previous version of this single line.

const insertHTMLAfter = (html, el) = > el.insertAdjacentHTML('afterend', html)
Copy the code

8. Scramble arrays

Shuffling a set of data is a common situation that you can encounter at any time in development, and unfortunately, it’s not built into JavaScript.

To that end, here’s a one-line shuffle code you can use every day:

const shuffle = arr= > arr.sort(() = > 0.5 - Math.random())
Copy the code

It takes advantage of the array’s sort method, which randomly sorts by inserting the next element before or after the previous one.

9. Get the selected text on the web page

The browser has a built-in method called getSelection on the global Windows object. Using this method, you can create a single line of code that returns the text selected by the box on the web page.

const getSelectedText = () = > window.getSelection().toString()
Copy the code

10. Get a random Boolean value

When programming, and especially when writing games, sometimes you want certain behaviors to be performed randomly. In this case, the following single line of code makes things very convenient.

const getRandomBoolean = () = > Math.random() >= 0.5
Copy the code

The code above has a 50/50 chance of returning true or false, because the probability of generating a random number greater than 0.5 is equal to the probability of generating a random number less than 0.5.

But, for example, if you wanted a random Boolean value with a probability of 70% false, you could simply change 0.5 to 0.7, and so on.

11. Average the array

There are many ways to average an array, but the logic is the same in each. You have to take the sum of the array and its length and divide it to get the average.

const average = (arr) = > arr.reduce((a, b) = > a + b) / arr.length
Copy the code

In the single line of code, Average, we use Reduce so that we can get the sum of the array in a single line instead of using a loop. And then we divide that by the length of the array, and that’s the average of the array.


That’s all, everybody! You’ve now seen 11 simple but powerful single lines of JavaScript code. I’ve tried to pick code that is less well known so you can learn new things. I use them every day, and I think you will, too.

Thank you for reading. If you liked this post, give it a thumbs up. If you have anything to say about this article, please leave a comment. See you in the next article.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.