DEV Community

Cover image for 20 JavaScript One-Liners That Will Help You Code Like a Pro

20 JavaScript One-Liners That Will Help You Code Like a Pro

Muhammad Ovi on May 08, 2021

JavaScript keeps growing and growing, opening doors for new "to be tech geeks" in the market as it's one of the easiest languages to start. (is it ...
Collapse
 
moopet profile image
Ben Sinclair

09 Toggle boolean

const toggleBool = (bool) => (bool = !bool);
Enter fullscreen mode Exit fullscreen mode

This could be simplified to

const toggleBool = b => !b;
Enter fullscreen mode Exit fullscreen mode

because you're not actually toggling the original boolean. I'm not sure it offers any benefit beyond using !b in the first place, though.

const uniqueArr = (arr) => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

I think that if you're going to use full words elsewhere, like isArray you should use it here, and make the function uniqueArray. Most of the time, I think if what you're wanting is a set, you should use it as a set. In those cases you probably don't need to convert it back to an array anyway!

To calculate the days between two dates,
we first find the absolute between two dates and then divide it with 86400000 which is equal to milliseconds in a single day

Except... days aren't always 86400 seconds long, and this will fail when times are close to daylight savings, for example. There's a reason date libraries are complicated :)

Collapse
 
ovi profile image
Muhammad Ovi

Woah, man!
This is really helpful, I appreciate your effort <3

Collapse
 
aminnairi profile image
Amin

Hi there, really cool one-liners! My favorite is the true type one. I actually use it in almost all of my projects.

I'm not sure about the isArray though. This is indeed a one-liner, but in my opinion, it does not add much, besides being a shorter named version of the verbose Array.isArray. Wrapping a function that does exactly what you want with another function seems overkill to me. Don't you think?

Otherwise, great job!

Collapse
 
matthewadams profile image
Matthew Adams

Just use typeof

Collapse
 
andreykalechev profile image
Leechy

nope:

typeof []
// "object"
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
matthewadams profile image
Matthew Adams

An array is an object. Whether it's an Array is a separate question. I suppose if trueTypeOf were documented, describing its semantics, it would be clearer. Remember, all, syntax doesn't convey everything. You also need semantics. :)

Collapse
 
ovi profile image
Muhammad Ovi

Yeah, sometimes it's handy to just call a function to check, rather than doing Array.isArray(arr) you know.

Collapse
 
galoelmer profile image
galoelmer

Symbol.toStringTag

Collapse
 
robinbastiaan profile image
Robin Bastiaan

Can you explain what this does and where you can put this in practice?

Thread Thread
 
galoelmer profile image
galoelmer

Check out this post for possible case use:
dev.to/cherif_b/using-javascript-t...

Collapse
 
matthewadams profile image
Matthew Adams

Um, why write trueTypeOf when you can just use the typeof operator?

typeof 'foobar' === 'string' // returns true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ovi profile image
Muhammad Ovi

This is helpful if we need to verify if 'foobar' is a string, but in some cases, we want to get the type instead of checking (verifying).

Collapse
 
djkim profile image
DJ Kim

Awesome article!
A couple suggestions though:

const isTabInView = () => !document.hidden; // Not hidden

and

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform); // to be a function like other examples

Collapse
 
ovi profile image
Muhammad Ovi • Edited

Missed it there, thanks for the suggestions!
Made changes accordingly.

Collapse
 
chriskingwebdev profile image
ChrisKingWebDev

Be careful not to go too crazy with one liners. If you or a team mate has to dig back into the code after 6 months or a couple years, it can take some brain power to parse out what is happening.

If you are using a build process, the code is going to be minified and optimized in ways that are basically illegible to humans.

Code readability is my primary metric for good work.

Collapse
 
ovi profile image
Muhammad Ovi

Agreed 🤞

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi Muhammad, I think there is an issue with the longhand form of your bonus snippet. If name is null, undefined or an empty string (in fact any value) the variable fullName will be assigned. I think your intention was for fullName only to be assigned when

(name !== null && name !== undefined && name !== '')
Enter fullscreen mode Exit fullscreen mode

An alternative form of this condition using De Morgan's Law to invert the logic is...
(notice the initial not operation in the following condition)

(!(name !== null || name !== undefined || name !== '')
Enter fullscreen mode Exit fullscreen mode

Also, there is a good argument here for cohesive-equality because null == undefined. The following is equivalent.

(!(name == null || name !==''))
Enter fullscreen mode Exit fullscreen mode

Best regards.

Collapse
 
phuocng profile image
Phuoc Nguyen

Thanks for sharing. I always think these 1-liners are useful, so I made this site 1loc.dev.
Hopefully it's useful for you as well.

Collapse
 
jonrandy profile image
Jon Randy 🎖️
const isEven = i=>!(i%2)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ovi profile image
Muhammad Ovi • Edited

That's good. But it will return true if we call it with no argument

Collapse
 
johandalabacka profile image
Johan Dahl

15 and 16 doesn't work with multi character emojis

> truncateString('Hello 😀 How are you?', 10)
'Hello �...'
Enter fullscreen mode Exit fullscreen mode

You could use Array.from first to convert the string into an array of strings each holding a single character

const truncateString = (string, length) => {
  const chars = Array.from(string)
  return chars.length < length ? string : `${chars.slice(0, length - 3).join('')}...`;
};
Enter fullscreen mode Exit fullscreen mode

This will work correctly

> truncateString('Hello 😀 How are you?', 10)
'Hello 😀...'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
johnbo100 profile image
John Jones

Very useful. thank you

Collapse
 
ovi profile image
Muhammad Ovi

Glad you liked it <3

Collapse
 
ansonznl profile image
九旬

Hello, your article is great. Can I translate it to Chinese community website? I will indicate the source and author.

Collapse
 
ovi profile image
Muhammad Ovi

I would love it 😉

Collapse
 
frondor profile image
Federico Vázquez

In code reviews, I won't ever call someone a "pro" because he/she writes "one-liners". All the opposite.

Collapse
 
ovi profile image
Muhammad Ovi

Me neither.