Code Like a Pro using these 10 JavaScript One-Liners

Ashiq
Updated 20 Apr 2022

There's hell lot of way to strip down bunch of lines with just few keywords in JavaScript. Its built-in methods allow us write short, easily readable code, yes only if we are aware of them. Here we are taking this simplicity another step forward to see where you can write one-line solutions to some common use cases and problems you’d encounter in web development. Steal these one-liners pro code to write quick and simple code for your applications to make your code clean simple and don't give a chance to code reviewer.

1. Generate a random hex color

Default avatar can be a random color and user name's initial. So this one line code will generate a random hex color value for you.

const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomHexColor() // #eb06a7

2. Copy to Clipboard

Copy to clipboard is a must for almost every web apps may be for copying referral links or for copying API secrets its a good UX practice to include this feature wherever possible.

const copyToClipboard = (text) =>
  navigator.clipboard.writeText(text).then(() =>  console.log('Copied'), (err) =>  console.error('Error: ', err));

copyToClipboard("X Byte Lab");

3. Scroll To Bottom/Top

JavaScript's inbuilt method scrollIntoView allows us to quickly jump into view.
Add behavior: "smooth" for a smooth scrolling animation.

const scrollToView = (element, block="start") => element.scrollIntoView({ behavior: "smooth", block});

const element = document.getElementById("content");
scrollToView(element,"start");
scrollToView(element,"end");

4. Detect Dark Mode

User loves dark mode. Research from Android Authority revealed similar results, with 91% of participants prefers dark mode.

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

5. Remove duplicate values in an array

Every language has its own implementation of Hash List, in JavaScript, it is called Set. You can easily get the unique elements from an array using the Set Data Structure.

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

console.log(removeDuplicates([1, 1, 2, 3, 3, 4, 5, 6, 6])) 
// [1, 2, 3, 4, 5, 6]

6. Truncate a number to a fixed decimal point

May a times while dealing with currency we require truncation of decimal points. Using the Math.round() method, we can truncate a number to a certain decimal point.

const round = (n, d) =>Number(Math.round(n + "e" + d) + "e-" + d)

round(45.006, 2) //45.01
round(34.333, 2) //34.33

7. Generate a random string

Unique ID can be generated using Math.random to generate a random string.

// for alphanumeric
const randomString = () => Math.random().toString(36).slice(2)

// for string of number
const randomNumber = () => Math.random().toString(10).slice(2)

randomString() // mxs767r572m
randomNumber() // 4911864279800915

8. Convert a string to camelCase/PascalCase

This piece of code can be used to convert a string to camelCase or pascal case.

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));

toCamelCase('margin-top'); // marginTop
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_root_Element'); // RootElement
toCamelCase('main_block'); // mainBlock

9. Flatten an array

Often asked in interviews, which can be achieved with the code as follows.

const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])

flat(['apple', ['mango', 'banana']]) // ['apple', 'mango', 'banana']

10. Remove falsy values from array

We can remove all falsy value at once using array.filter(Boolean), we will be able to filter out all falsy values in the array.

const removeFalsy = (arr) => arr.filter(Boolean)

removeFalsy(['' ,false, 0, 'a string', true, '', NaN, 5, undefined, 'string 2', false])// ['a string', true, 5, 'string 2']


That's all for now, these are some of the one-liner JavaScript codes that you help you write code like a pro.