Awesome javascript one-liners to look like a pro

Avatar image of
Posted by admin

Learn some great one-liners to use on your next project

Javascript syntax and built-in methods allow us to cut down a lot of unnecessary lines in our code and write short, easily readable code. In this post, 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. Don’t hesitate to steal these 15 Javascript one-liners to write quick and simple code for your applications.

Reverse a String

You can reverse a string in one line using splitjoin, and reverse methods.

const stringReverse = str => str.split("").reverse().join("");

stringReverse("Welcome to Javascript")
//tpircsavaJ ot emocleW

Get the Average of an Array of Number

Javascript reducer allows calculating the average of a number of arrays in a single line.

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

average([21, 56, 23, 122, 67])

Reduce method is quite useful when writing one-line solutions to a number of problems like finding the sum or maximum in an array of numbers.

Get an Array of Past Seven Days

Do you want to use an array of the past seven days (including today) in your program? This Javascript code easily creates the array in only one line.

const pastWeek = [...Array(7).keys()].map(days => new Date( - 86400000 * days))

If you use a plus sign in place of minus, you can get an array with the next seven days. And it doesn’t have to be only the dates of the last week. You can get the dates of the 7 days before/after any date by replacing with it.

Note that 86400000 used here is the number of milliseconds in a day.

Capitalize a String

Even though Javascript doesn’t provide a built-in capitalize method, writing our own method to capitalize a string takes only one line.

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

capitalize("javascript one-liners are fun")
//Javascript one-liners are fun

Remove Duplicates in an Array

We know that sets in Javascript only store unique items. We can use this behavior to our advantage to remove duplicate items in an array. However, it only works with arrays storing primitive data. So you’d have to write a multiline solution to remove duplicates in arrays storing objects. But, still, it’s a quite decent method to remove duplicates in simple scenarios.

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

removeDuplicates([31, 56, 12, 31, 45, 12, 31])
//[ 31, 56, 12, 45 ]

Round Decimals to a Certain Number of Decimal Places

Rounding decimals to a fixed number of decimal points is a tricky business in Javascript. Even though the built-in toFixed() method can easily do this conversion, it gives weird results in some cases because of the way floating-point arithmetics work.

Number((2.935).toFixed(2)) //2.94
Number((12.349345).toFixed(4)) //12.2493
Number((2.5398).toFixed(3)) //2.540

Number((1.005).toFixed(2)) //outputs 1 instead of 1.01
Number((1.555).toFixed(2)) //outputs 1.55 instead of 1.56

To avoid this unexpected behavior in our code, we can represent the numbers in exponential notation and use Math.round() to get the decimal rounded to a given number of decimal places.

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

round(1.005, 2) //1.01
round(1.555, 2) //1.56

Generate a Random ID

This simple function generates a random ID using Math.random(). Since Math.random() doesn’t guarantee that all the generated numbers are unique, this method is not 100% secure to use in production. But there’s no harm in using it during development to quickly get an ID to complete the implementation and test the app.

const randomID = Math.random().toString(36).substring(2)

Check If the User has Scrolled to the Bottom of the Page

If you want to display/execute something when the user scrolls to the bottom of the page, use this to find whether the user is currently at the bottom.

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight

Toggle Display of an Element

You can easily toggle between hiding and displaying an element with the single line method.

const toggle = element => = ( === "none" ? "block" : "none")

Generate a Random Hex Color

This method generates a random hex code using Math.random() and padEnd(). Use this whenever you want to display a random color in your program.

const hexColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')

Scroll to the Top of the Page

You can scroll to the top of the page in Javascript using scrollTo() method. It accepts the X and Y coordinates of the position Javascript should scroll to. So when we pass zero to X and Y, it scrolls to the top of the page.

const toTop = () => window.scrollTo(0, 0)

Get the Number of Days Between Two Days

In this single-line implementation, you should convert the two days into time-based representation and then find their difference. You can then divide it by the number of milliseconds in a day to get the number of days.

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

dayDif(new Date("2020-09-23"), new Date("2020-10-01"))

Clear All Cookies

You can clear all the cookies stored by the application by setting their expiry date to a date that has already passed. So if you set the expiry date to the first date in the Javascript time system, the system automatically expires the cookie. And you can clear the data stored in cookies along with the previous step.

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));

Strip HTML From Text

When accepting user inputs and in other use cases, you might want to strip any HTML elements in the text you process. With the help of DOMParser, this is only one line.

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || ''

Detect Dark Mode

Finally, if you want to detect whether the user has enabled dark mode in their browser, use this one-line solution.

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

Final Words…

In this post, we gave you 15 one-line Javascript solutions to problems that we commonly encounter in frontend development. I hope you found these solutions interesting. And don’t forget to use them to reduce the number of lines in your code. Or even to look cool!

Thanks for reading!

Source: livecodestream

Leave a Reply

Your email address will not be published. Required fields are marked *