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

Detailed graphic explanation of MySql5.7.18 character set configuration

Background: A long time ago (2017.6.5, the articl...

How to make a centos base image

Preface Now the operating system used by my compa...

MySQL database operation and maintenance data recovery method

The previous three articles introduced common bac...

MySql 8.0.11 installation and configuration tutorial

Official website address: https://dev.mysql.com/d...

Detailed explanation of JavaScript function this pointing problem

Table of contents 1. The direction of this in the...

Linux CentOS6.9 installation graphic tutorial under VMware

As a technical novice, I am recording the process...

A brief discussion on the understanding of TypeScript index signatures

Table of contents 1. What is an index signature? ...

Solutions to browser interpretation differences in size and width and height in CSS

Let’s look at an example first Copy code The code ...

nginx automatically generates configuration files in docker container

When a company builds Docker automated deployment...

How to view and clean up Docker container logs (tested and effective)

1. Problem The docker container logs caused the h...

The neglected special effects of META tags (page transition effects)

Using js in web design can achieve many page effec...

Solution to the problem that Navicat cannot remotely connect to MySql server

The solution to the problem that Navicat cannot r...

Mac node deletion and reinstallation case study

Mac node delete and reinstall delete node -v sudo...

Write a publish-subscribe model with JS

Table of contents 1. Scene introduction 2 Code Op...