Skip to content

Javascript One Liners

Posted on:February 12, 2023

A few years ago I started this gist of javascript one liners. I’ve been adding to it over the years and thought it would be fun to share it here.

⚡️ Here they is:

//  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
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

// 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 of page
const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });
// Scroll to bottom of page
const scrollToBottom = () => window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });

// Scroll to top of an element
const scrollToEl = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
// Scroll to elements bottom
const scrollToElb = (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();

// Simple star rating ex: rating(5) will print ★★★★★
const rating = star => "".repeat(Math.max(0, Math.min(star, 5))).padEnd(5,"" );

Note: this is just for fun, there are no benefits in your code only being on one line, always aim for readability over cleverness (although that star rating and random color snippet is p. cool)

Edit on Github
More Posts