These are our favorite one-liners that we've used and forgot existed because they work so well 😁.
Generate a random hex color
const color = () => '#' + Math.floor(Math.random() * (0xffffff + 1)).toString(16).padEnd(6, '0');
Remove array duplicates
const removeDuplicates = arr => [...new Set(arr)];
Reverse a string
const reverseString = str => [...str].reverse().join()
Clear all cookies
Note: This will not always work because cookies can be set to not be changed from the front-end. (Thanks @lukeshiru!)
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, '=;expires=${new Date(0).toUTCString()};path=/'));
Remove falsy values from an array
const removeFalsyValues = arr => arr.filter(x=>x)
/** OR **/
const removeFalsyValues = arr => arr.filter(Boolean)
Get the value of a query parameter from a url
Pass in the url and the parameter that you're looking for the value of, and this function will return the value to you
const getQueryParam = (url, param) => new URL(url).searchParams.get(queryParam);
Copy to clipboard
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
Get selected text
const getSelectedText = () => window.getSelection().toString();
Scroll to Top
const scrollToTop = () => window.scrollTo(0, 0);
Scroll to Bottom
const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
Toggle a Boolean
const toggleBool = bool => !bool;
Convert Fahrenheit / Celsius
const cToF = (celsius) => celsius * 9/5 + 32;
const fToC = (fahrenheit) => (fahrenheit - 32) * 5/9;
Check if a property exists on an object
I know this seems like more than a one-liner, but given an object already exists, checking for properties on that object is definitely a one-liner 😁
const myObject = {
id: 1,
name: 'Tron',
group: 'decepticons'
};
const isGroupExists = 'group' in myObject;
console.log(isGroupExists); // true
const isMusicExists = 'music' in myObject;
console.log(isMusicExists); // false
Thanks
Special thanks to Fernando, José, @patricia_br, @lukeshiru, @lionelrowe and @jonrandy for adding to this list and optimizing!
Top comments (12)
Math.floor(Math.random() * 0xffffff)
gives numbers in the range0..0xfffffe
, not0..0xffffff
. You wantMath.floor(Math.random() * (0xffffff + 1))
, i.e.Math.floor(Math.random() * 0x1000000)
😉this guy hexes...
Reverse string can be shortened to:
Your version also has an issue with unicode, which the above function fixes:
Filtering falsy values can also be shortened:
niiiiiice
Cool really helped me!
sweet! thanks for the feedback!
🔥
JavaScript's magic
Filtering falsy values can also be done like...
const removeFalsyValues = arr => arr.filter(Boolean)
Thanks for your good article!
we actually had it this way originally 😄. both ways work, i think the updated one may save a character or two. i'll add a note, so that both are covered though!
Really cool
Thanks!
Some comments have been hidden by the post's author - find out more