What would you do if you wanted to impress a professional developer? Simple: solve a complex problem with simple logic and as few lines of code as possible. With the introduction of ES6 arrow functions, it is possible to create one-liners that look elegant and simple.
In today’s article, I’ll work with you to learn 11 rare but powerful one-liners. Now, get ready, let’s get started!
1. Get the number of characters in a string
Getting the count of characters is a useful utility in many cases, we can use it to get the number of spaces and subsequent words, or this can be used to get the count of a certain delimiter in a string.
const characterCount = ( str , char ) => str . split ( char ). length - 1
The idea is simple, we split the string using the passed parameter char and get the length of the returned array. Since each time the string is split, there is one more than the splitter; so subtract 1 and we have a single line of characterCount.
2. Check if the object is empty
Checking for nullability of an object is actually a lot harder than it looks, every time checking if an object is equal to {} will return even if the object is null
…
The post 11 Rare JavaScript One-liners That Will Surprise You first appeared on Lenix Blog .
This article is reprinted from https://blog.p2hp.com/archives/9035
This site is for inclusion only, and the copyright belongs to the original author.