DEV Community

Cover image for 7 JavaScript One Liners to look like a pro
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

7 JavaScript One Liners to look like a pro

Hello Folks πŸ‘‹

What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer. I love building web applications with different technologies.

Today, I am here with some good JS one-liners for you to look like a pro that might help you in your next project. Let's go πŸš€


Toggle Boolean

Toggling boolean, turning true to false or vice versa.

const toggleBool = (val) => (val = !val)

toggleBool(false) //true
Enter fullscreen mode Exit fullscreen mode

Random Boolean

Generate a random boolean.

const randomBool = () => Math.random() >= 0.5;

randomBool() //true
Enter fullscreen mode Exit fullscreen mode

Scroll to Top

Scroll to the top of the page.

const scrollToTop = () => window.scroll(0,0)
Enter fullscreen mode Exit fullscreen mode

Detect dark mode

Returns true when dark mode is enabled.

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
Enter fullscreen mode Exit fullscreen mode

Get user-selected text

Returns the selected text.

const getSelectedText = () => window.getSelection().toString();
Enter fullscreen mode Exit fullscreen mode

Difference between two dates

const dif = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)

dif(new Date("2006-02-24"), new Date ("2022-02-24"))
Enter fullscreen mode Exit fullscreen mode

Random HEX color

const hexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
Enter fullscreen mode Exit fullscreen mode

This was it for this article, I hope this article helped you. Feel free to share more in the comments below.
Thank you for reading!

I am on Twitter @codewithsnowbit. Give it a follow.

Let's Connect 🌏

Top comments (1)

Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ • Edited
const toggleBool = (val) => (val = !val)
Enter fullscreen mode Exit fullscreen mode

This one-liner will definitely not make you look like a pro, but like someone who really enjoys typing.

Just write

!bool
Enter fullscreen mode Exit fullscreen mode

instead of

toggleBool(bool)
Enter fullscreen mode Exit fullscreen mode

And the assignment (val = !val) is completely useless here; it assigns to a variable that gets discarded anyway.