18 killer JavaScript one-liners

18 killer JavaScript one-liners

Preface

JavaScript continues to grow and prosper because it is one of the easiest languages ​​to pick up, thus opening the door for new tech geeks in the market.

And, whether you’re new to JavaScript or a more of a professional developer, learning something new is always a good thing.

This article has compiled some very useful one-liners that can help you improve your work efficiency.

What is a one-line code?

One-liners are a coding practice where we perform some functionality with just one line of code.

One-line code example

1. Copy to clipboard

Use navigator.clipboard.writeText to easily copy any text to the clipboard.

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");

2. Check if the date is valid

Use the following code snippet to check whether a given date is valid or not.

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true

3. Find out the day of the year

Find the day of a given date.

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272

4. Capitalize the first string

Javascript does not have a built-in uppercase function, so we can use the following code.

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)capitalize("follow for more") // Result: Follow for more

5. Find the number of days between two dates

Use the following code snippet to find the number of days between the given 2 dates.

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)dayDif(new Date("2020-10-21"), new Date("2021-10-22"))// Result: 366

6. Clear all cookies

You can easily clear all cookies stored in a web page by accessing the cookies using document.cookie and clearing it.

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

7. Generate random hexadecimal

You can use Math.random and the padEnd property to generate random hexadecimal colors.

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHex());
//Result: #92b008

8. Remove duplicates from an array

You can easily remove duplicates using Set in JavaScript.

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]

9. Get query parameters from URL

You can retrieve query parameters from the url easily by passing window.location or the original URL goole.com?search=easy&page=3

const getParameters = (URL) => {
 URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\"').replace(/&/g, '","').replace(
 /=/g, '":"') + '"}');
 return JSON.stringify(URL);
};
getParameters(window.location) // Result: { search : "easy", page : 3 }

10. Record time from date

We can record the time in the format hours::minutes::seconds from a given date.

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"

11. Check if a number is even or odd

const isEven = num => num % 2 === 0; console.log(isEven(2));
 // Result: True

12. Find the average of numbers

Use the reduce method to find the average between multiple numbers.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5

13. Reverse a string

You can easily reverse a string using the split, reverse, and join methods.

const reverse = str => str.split('').reverse().join('');reverse('hello world'); 
// Result: 'dlrow olleh'

14. Check if the array is empty

A simple one-liner that checks if an array is empty will return true or false.

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true

15. Get the selected text

Use the built-in getSelectionproperty to get the text selected by the user.

const getSelectedText = () => window.getSelection().toString();
getSelectedText();

16. Shuffle the array

It is very easy to shuffle an array using the sort and random methods.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4])); // Result: [ 1, 4, 3, 2 ]

17. Detect dark mode

Use the following code to check if the user's device is in dark mode.

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matchesconsole.log(isDarkMode) // Result: True or False

18. Convert RGB to Hexadecimal

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);rgbToHex(0, 51, 255); // Result: #0033ff

Summarize

This is the end of this article about JavaScript one-line code. For more relevant JavaScript one-line code content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 25 JavaScript one-line codes commonly used in development (summary)
  • js to achieve a single line of text scrolling up effect example code
  • js single line message scrolling code, you can add countless
  • Share 20 JavaScript one-line codes

<<:  Some common mistakes with MySQL null

>>:  Beginners learn some HTML tags (3)

Recommend

MySQL password modification example detailed explanation

MySQL password modification example detailed expl...

Some tips for using less in Vue projects

Table of contents Preface 1. Style penetration 1....

About deploying a web project to Alibaba Cloud Server (5 steps to do it)

1. First log in to the Alibaba Cloud website to r...

A brief talk about Rx responsive programming

Table of contents 1. Observable 2. Higher-order f...

MySQL cross-table query and cross-table update

Friends who have some basic knowledge of SQL must...

How to solve the problem of FileZilla_Server:425 Can't open data connection

When installing FileZilla Server on the server, t...

SQL Optimization Tutorial: IN and RANGE Queries

Preface "High Performance MySQL" mentio...

Steps to install RocketMQ instance on Linux

1. Install JDK 1.1 Check whether the current virt...

Linux general java program startup script code example

Although the frequency of starting the shell is v...

Vue uses custom instructions to add watermarks to the bottom of the page

Project Scenario Add a custom watermark to the en...

Detailed usage of docker-maven-plugin

Table of contents Docker-Maven-Plugin Maven plugi...

13 Most Frequently Asked Vue Modifiers in Interviews

Table of contents 1. lazy 2.trim 3.number 4.stop ...