DEV Community

Cover image for 20 Killer JavaScript One Liners ☝️
Savio Martin
Savio Martin

Posted on Edited on

20 Killer JavaScript One Liners ☝️

Hello Folks 👋

This is Savio here. I'm young dev with an intention to enhance as a successful web developer. I love building web apps with React. I have proved my superiority in frontend technologies.

Today, I'd like to share 20 Killer JavaScript one liners to make your life easier. Let's goooo 🚀


Get Value of a brower Cookie

Retrieve the value of a cookie by accessing with document.cookie

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Convert RGB to Hex

const rgbToHex = (r, g, b) =>
  "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255); 
// Result: #0033ff
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Copy to Clipboard

Easily copy any text to clipboard using navigator.clipboard.writeText.

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

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("December 17, 1995 03:24:00");
// Result: true
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

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
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Capitalise a String

Javascript doesn't have an inbuilt capitalise function, so we can use the following code for the purpose.

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// Result: Follow for more
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Find the number of days between two days

Find the days between 2 given days using the following snippet.

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

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).toUTCString()};path=/`));
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Generate Random Hex

You can generate random hex colors with Math.random and padEnd properties.

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

console.log(randomHex());
// Result: #92b008
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Remove Duplicated from Array

You can easily remove duplicates with Set in JavaScript. Its a life saver.

const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Get Query Params from URL

You can easily retrieve query params from a url either by passing window.location or the raw URL goole.com?search=easy&page=3

const getParameters = (URL) => {
  URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
  return JSON.stringify(URL);
};

getParameters(window.location)
// Result: { search : "easy", page : 3 }
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Log Time from Date

We can log time, in the format hour::minutes::seconds from a given date.

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Check if a number is even or odd

const isEven = num => num % 2 === 0;

console.log(isEven(2)); 
// Result: True
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Find Average of Numbers

Find the average between multiple numbers using reduce method.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Scroll to Top

You can use window.scrollTo(0, 0) method to automatic scroll to top. Set both x and y as 0.

const goToTop = () => window.scrollTo(0, 0);

goToTop();
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Reverse a string

You can easily reverse a string using split, reverse and join methods.

const reverse = str => str.split('').reverse().join('');

reverse('hello world');     
// Result: 'dlrow olleh'
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Check if array is empty

Simple one liner to check if an array is empty, will return true or false.

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);
// Result: true
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Get Selected Text

Get the text the user has select using inbuilt getSelection property.

const getSelectedText = () => window.getSelection().toString();

getSelectedText();
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Shuffle an Array

Shuffling an array is super easy with sort and random methods.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Detect Dark Mode

Check if a user's device is in dark mode with the following code.

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

console.log(isDarkMode) // Result: True or False
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Do you want to test your project?

Try LambdaTest, test your browers in 3000+ browers like that with an image of your website
Image description


👀 Wrapping Up

Yeah, that's a wrap. Hope you enjoyed the article. Do not hesitate to share your feedback. I am on Twitter @saviomartin7. Give a follow!

Follow me on Github @saviomartin, Don't miss my amazing projects! 💯

Feedbacks are greatly appreciated! 🙌 Have an amazing day!

🌎 Lets connect

Top comments (43)

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
jonrandy profile image
Jon Randy 🎖️ • • Edited
const rgbToHex = (...rgb)=>'#'+rgb.reduce((a,v)=>a+(256|v).toString(16).slice(1),'')
const rgbToHex = (...rgb)=>'#'+rgb.reduce((a,v)=>a+v.toString(16).padStart(2,0),'')

const randomHex = (a='facedb')=>[...a].reduce(x=>x+(a+0x3d00b615)[~~(Math.random()*16)],'#')
const randomHex = (f='reduce')=>[...f][f](a=>a+(~~(Math.random()*16)).toString(16),'#')
const randomHex = ()=>'#'+(~~(Math.random()*(1<<24))|1<<25).toString(16).slice(1)
const randomHex = ()=>'#'+(~~(Math.random()*(1<<24))).toString(16).padStart(6,0)
const randomHex = ()=>'#'+(~~(Math.random()*8**8)).toString(16).padStart(6,0)
// Anyone got any shorter?


const reverse = str=>[...str].reduce((a,v)=>v+a)

const isEven = x=>~x&1

const capitalize = ([a,...b])=>a.toUpperCase()+b.join('')
const capitalize = a=>a.replace(/./,a=>a.toUpperCase())
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

😊

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
Sloan, the sloth mascot
Comment deleted
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
lluismf profile image
Lluís Josep Martínez •

But who has the need in the real world / real apps to reverse a string? Nobody.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
webreflection profile image
Andrea Giammarchi •

Faster !== Correct ... his string reverse breaks with code points, while [...str] doesn't.

Try it: OP reverse breaks the emoji with reverse('some 💩'); while this reduce suggestion doesn't.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน Thread
 
webreflection profile image
Andrea Giammarchi • • Edited

P.S.

// this works fast and correct at the same time
const reverse = str => [...str].reverse().join('');
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน Thread
 
eioluseyi profile image
EIO • Emmanuel Imolorhe •

In a bid to be obnoxious 😏 you could have shortened your code further by 2 characters 🌚

const reverse = str => [...str].reverse().join``;
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
jonrandy profile image
Jon Randy 🎖️ • • Edited

I made no claim to it being faster, but in this case the reduce method is almost twice as fast - jsbench.me/3tkttupth4/1 - at least on Chrome. On Firefox though, the situation is reversed. Different JS engines, different optimisations I guess

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
silverium profile image
Soldeplata Saketos •

alternative reverse:

const reverse = str => [...str].reduceRight((a,v)=> a+v)
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

:D

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
siddharthshyniben profile image
Siddharth •

Nice list!

Some things I want to mention

  1. You forgot const (or let) in the first code block
  2. You can get URL Params easily in modern browsers like so: Object.fromEntries(new URLSearchParams(window.location.search))
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
dacurse profile image
DaCurse •

For 2, I think converting to an object is pointless, nothing wrong with the URLSearchParams object (which is basically a Map)

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
siddharthshyniben profile image
Siddharth •

But it's not an actual object (like arguments is not an actual array), so If you want to do some advanced object stuff you need to convert it to an object.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
lucascardim profile image
LucasCardim •

What do you mean with "I have proved my superiority in frontend technologies.". Be humble, you're not superior than anyone.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
lluismf profile image
Lluís Josep Martínez •

He has proved that he can copy paste from StackOverflow :-)

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
silverium profile image
Soldeplata Saketos •

but to distinguish the better code to copy is the hardest thing

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน Thread
 
codingjlu profile image
codingjlu •

Yes, especially when one post has 1k votes and another has -16?

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
ashu profile image
Ashutosh Sharma •

I believe English is not his primary language(not mine either). I guess he means skill/competency.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
zeys profile image
zeys •

Dont be hard on him he's just a kid (he's 14)

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
andrecastelo profile image
André Castelo •

He's 14

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
murtukov profile image
Timur Murtukov •

Nah, these are not killer one-liners, just a beginner level. Besides that, writing something in 1 line doesn't mean good. It can sometimes harm readability, for example the first snippet is just a good example of how NOT to write your code.

And some of the examples are pretty useless. Why would you create a function for window.scrollTo(0, 0)? It's short enough on its own to use it directly.

In fact you just stolen all these snippets either from 30secondsofcode.org/ or from StackOverflow (I checked) and you have audacity to call yourself "superior". If you are really "an enthusiastic frontend developer" as you call yourself, than go and learn instead of posting useless articles.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
andrecastelo profile image
André Castelo •

He's 14 though, give him a break.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
rahxuls profile image
Rahul •

hahah seriously?

go do a background research on him, 14 and oversmart and fooling on internet.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
tracygjg profile image
Tracy Gilmore •

Suggested alternative:
const capitalize = ([init, ...rest]) => init.toUpperCase() + rest.join('')

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
manoharreddyporeddy profile image
Manohar Reddy Poreddy •

Once I used to use JS to capitalize, and everything else.
Feedback comments came in from Experts
Now I just use the simpler CSS.
Ex: w3schools.com/cssref/pr_text_text-...

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
jonrandy profile image
Jon Randy 🎖️ • • Edited

That doesn't do the same thing, merely changes the appearance of the string on screen - doesn't change the string. Depending on the use case, that could be okay

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
manoharreddyporeddy profile image
Manohar Reddy Poreddy •

Yes, but that was an example (Ex:) for conversation.
I used to do everything in JS
including building accessible menus, etc
wrote several 100s of lines of code for each.
In CSS, it was always less than 50 each, very easy to change, and by everyone.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
jonrandy profile image
Jon Randy 🎖️ • • Edited

I think there is also an issue with your randomHex function - it will never return #ffffff since:

Math.floor(Math.random() * x)
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

can only ever return values from 0 to x-1. You need to use Math.round()

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
0826gm profile image
0826gm •

Array shuffling this way won't be statistically random, it's biased due to how sort works with non-deterministic compare function. I propose changing the snippet to the similar

const shuffleArray = (arr) => arr.map(e => [Math.random(), e]).sort((a,b) => a[0] - b[0]).map(e => e[1]);
⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

...which assigns a random "position" to each element, compares by those, then discards them.

There are even better ways (O(n)).

For more on this, see stackoverflow.com/q/2450954/8376184

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
mellen profile image
Matt Ellen-Tsivintzeli • • Edited

This has come up before!

Nice post. Be aware that shuffling an Array like this is not perfectly random and a proper implementation is a little more complicated: medium.com/@nitinpatel_20236/how-t...

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
erickpetru profile image
Erick Eduardo Petrucelli •

Since line breaks are optional in JavaScript, any code can be one line if you want to. 🤣

Ok, jokes aside, I understand one liner functions have appeal with developers, since Functional Programming is receiving full love nowadays.

So if anyone here needs to convert browser's rgb string to hex: stackoverflow.com/a/3627747/424498. This way you can directly send the result of a getComputedStyle(someElement).backgroundColor call to the one line function and receive the hex string as result.

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน
 
duzun profile image
Dumitru Uzun •

Shorter:

const isDateValid = (...val) => !Number.isNaN(+new Date(...val));
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / 86400000);
const randomHex = () => `#${((1<<24)|Math.random() * 0xffffff).toString(16).slice(1)}`;

⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน ⭐ Must Read: saviomartin/ killer javascript one liners f - ประเด็นร้อน

Some comments may only be visible to logged-in visitors. Sign in to view all comments.