7 Killer JavaScript One Liners
As JavaScript is one of the most popular languages, there are a ton of libraries out there.
JavaScript syntax and built-in methods allow us to cut down a lot of unnecessary lines in our code and write short, easily readable code.
In this article, you will learn 7- one liners that are kind of rare to find, yet so powerful. Then, get ready, and let’s start with the first one!

1. Check If Date Is Valid
Use The Following Snippet To Check If A Given Date Is Valid Or Not.
* * *
const isDateValid = (… val) ⇒ ! Number. isNaN(new Date… val). valueof ());
isDateValid( “October 17, 2021 03:24:00 “);
/ /Result: true
2. Find The Day Of Year
Find Which Is The Day By A Given Date.
* * *
const dayofYear = (date)⇒
Math.floor( (date – new Date(date. getFullYear (),
0, 0))/ 1000 / 60/ 60/ 24);
dayofYear(new Date());
/ / Result: 272
3. Copy To Clipboard
Easily Copy Any Text To Clipboard Using Navigator.Clipboard.WriteText .
* * *
const copyToClipboard = (text) ⇒
navigator.clipboard. writeText(text) ;
copy To Clipboard(“Hello World”);
4. Clear All Cookies
You Can Easily Clear All Cookies Stored In A Web Page By Accessing The Cookie Using Document.Cookie And Clearing It.
* * *
const clearCookies = document.cookie.split(‘; ‘).forEach(cookie
⇒ document.cookie = cookie.replace(/^ +/, ‘ ‘). replace( /=.*/,’=;expires=${new Date(0) . to UTC String()};path=/’);
5. Generate Random Hex
You Can Generate Random Hex Colors With Math.Random And PadEnd Properties.
* * *
const randomHex = () ⇒ ‘#${Math. floor (Math.random()*
0 x f f f f f f). tostring(16). padEnd(6, “0”)}’;
console.log(randomHex());
/ / Result: #92b008
6. Check If A Number Is Even Or Odd
* * *
const is Even = num ⇒ num % 2 ≡ 0;
console.log(isEven(2));
// Result: True
7. Get Selected Text
Get The Text The User Has Select Using Inbuilt GetSelectionproperty.
* * *
const getselectedText = () ⇒ window. getselection(). tostring();
getselectedText () ;