Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
πŸ‘‘ Awesome one-liners you might find useful while coding.
// Inspired by https://twitter.com/coderitual/status/1112297299307384833 and https://tapajyoti-bose.medium.com/7-killer-one-liners-in-javascript-33db6798f5bf
// Remove any duplicates from an array of primitives.
const unique = [...new Set(arr)]
// Sleep in async functions. Use: await sleep(2000).
const sleep = (ms) => (new Promise(resolve => setTimeout(resolve, ms)));
// or
const sleep = util.promisify(setTimeout);
// Type this in your code to break chrome debugger in that line.
debugger;
// Just plain english.
[...].every(Number.isFinite);
// Returns all non-falsy values from an array.
[...].filter(Boolean)
// Array destructuring to see matching elements.
let [r, g, b, a] = [255, 0, 0, 255];
// Object destructuring to reduce multiple lines of code to a single line.
let {width, height} = resolution;
// Gets an item from the list and wraps around to the start if n is larger than the list.
items[n % items.length]
// Console.log in array function without adding curly braces.
const addFortyTwo = number => console.log(number) || number + 42
// Same as above
const add42 = n => (console.log(n), n + 42);
// Log variables with names. I love this trick with object ❀️
console.log({ a, b, c, d, e});
// Random hex color
'#'+(~~(Math.random()*0xffffff)).toString(16).padEnd(6,0)
// or
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
// We love Javascript that's why instead of Math.floor we use
// Note: Use with caution, it won't work for big (>32bit) or negative numbers
~~anyNumber
// Shuffle Array
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));
// Copy to Clipboard
const copyToClipboard = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
copyToClipboard("Hello World!");
// Unique Elements
const getUnique = (arr) => [...new Set(arr)];
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr));
// Detect Dark Mode
const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode());
// Scroll to Top
const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
// Scroll To Bottom
const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
// Check if an element is focused
const elem = document.querySelector(' .text-input');
const isFocus = elem == document.activeElemnt;
// Check if an array is empty
let arr = [1,2,3,4];
const arrIsEmpty = !(Array.isArray(arr) && arr.length > 0);
// Redirect user
const redirect = url => location.href = url // ex: recdirect("https://google.com")
// Go back to previous page
const navigateBack = () => history.back();
// Get selected text
const getSelectedText = () => window.getSelection().toString();
@mrhammadasif
Copy link

mrhammadasif commented Apr 2, 2019

Some love from my side to do Math.ceil πŸ˜„
-~63.16

@mrhammadasif
Copy link

mrhammadasif commented Apr 2, 2019

Your Hex Color generator code randomly generate invalid color codes as well e.g. (#34556, #aabbc). Replace this with this to fix it

'#'+(~~(Math.random()*0xffffff)).toString(16).padEnd(6,0)

@voila
Copy link

voila commented Apr 2, 2019

const add42 = n => (console.log(n), number + 42); should be const add42 = n => (console.log(n), n + 42);

@jordrake
Copy link

jordrake commented Apr 2, 2019

const observe = obj => new Proxy(obj, { get: (t, k) => (console.log(k), t[k]) } )

It will return a new object that will act like obj but also logs when properties are accessed, useful for debugging. Logs for gets only, easily extended for sets but gets a bit verbose for one line.

@designerzen
Copy link

designerzen commented Apr 2, 2019

Don't use ~~Number for big (>32bit) or negative numbers - they are not equivalent!

In fact, I wouldn't recommend using it at all as the performance improvement is negligable and the error margin is large, and very challenging to debug.

@kamoroso94
Copy link

kamoroso94 commented Apr 2, 2019

Correction: you should multiply by 16777216, and pad the start with 0's.

// Random hex color
const randColor = () => '#' + Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, 0)

@gaoryrt
Copy link

gaoryrt commented Apr 3, 2019

// array from 0 to n - 1
const arr = n => [...Array(n).keys()]
arr(5) // [0, 1, 2, 3, 4]

@revelt
Copy link

revelt commented Apr 3, 2019

imho first one was best

@benjamingr
Copy link

benjamingr commented Apr 3, 2019

const sleep = (ms) => (new Promise(resolve => setTimeout(resolve, ms)));

This can be

const sleep = util.promisify(setTimeout);

@martinsebastian
Copy link

martinsebastian commented Apr 3, 2019

In devtool console I often fancy console.log.bind(console) for pointless logging out args from callbacks.

Like somePromise().then(console.log.bind(console));

Most of the time I use it for REST requests or event observers or simply to test out some quick proof of concept when mutating data.

@lxsmnsyc
Copy link

lxsmnsyc commented Apr 4, 2019

You can also inline variable assignments and get the assigned value at the same time:

let flag;

const toggleFlag = () => ( flag = !flag );

console.log(toggleFlag()); // true
console.log(toggleFlag()); // false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment