VDone Demo VDone Demo
Home
  • Articles

    • JavaScript
  • Study Notes

    • JavaScript Tutorial
    • Professional JavaScript
    • ES6 Tutorial
    • Vue
    • React
    • TypeScript: Build Axios from Scratch
    • Git
    • TypeScript
    • JS Design Patterns
  • HTML
  • CSS
  • Technical Docs
  • GitHub Tips
  • Node.js
  • Blog Setup
  • Learning
  • Interviews
  • Miscellaneous
  • Practical Tips
  • Friends
About
Bookmarks
  • Categories
  • Tags
  • Archives
GitHub (opens new window)

Nikolay Tuzov

Backend Developer
Home
  • Articles

    • JavaScript
  • Study Notes

    • JavaScript Tutorial
    • Professional JavaScript
    • ES6 Tutorial
    • Vue
    • React
    • TypeScript: Build Axios from Scratch
    • Git
    • TypeScript
    • JS Design Patterns
  • HTML
  • CSS
  • Technical Docs
  • GitHub Tips
  • Node.js
  • Blog Setup
  • Learning
  • Interviews
  • Miscellaneous
  • Practical Tips
  • Friends
About
Bookmarks
  • Categories
  • Tags
  • Archives
GitHub (opens new window)
  • JavaScript文章

    • 33 Extremely Useful JavaScript One-Liners
      • 1. Date Handling
        • 1. Check Whether a Date Is Valid
        • 2. Calculate the Number of Days Between Two Dates
        • 3. Find the Day of the Year for a Given Date
        • 4. Format Time
      • 2. String Handling
        • 1. Capitalize the First Letter of a String
        • 2. Reverse a String
        • 3. Generate a Random String
        • 4. Truncate a String
        • 5. Strip HTML from a String
      • 3. Array Handling
        • 1. Remove Duplicates from an Array
        • 2. Check Whether an Array Is Empty
        • 3. Merge Two Arrays
      • 4. Number Operations
        • 1. Check Whether a Number Is Odd or Even
        • 2. Calculate the Average of a Set of Numbers
        • 3. Get a Random Integer Between Two Integers
        • 4. Round a Number to a Specified Number of Decimal Places
      • 5. Color Operations
        • 1. Convert RGB to Hexadecimal
        • 2. Generate a Random Hexadecimal Color
      • 6. Browser Operations
        • 1. Copy Content to the Clipboard
        • 2. Clear All Cookies
        • 3. Get the Selected Text
        • 4. Detect Dark Mode
        • 5. Scroll to the Top of the Page
        • 6. Check Whether the Current Tab Is Active
        • 7. Check Whether the Current Device Is an Apple Device
        • 8. Check Whether the Page Has Been Scrolled to the Bottom
        • 9. Redirect to a URL
        • 10. Open the Browser Print Dialog
      • 7. Miscellaneous
        • 1. Generate a Random Boolean
        • 2. Swap Variables
        • 3. Get the Type of a Variable
        • 4. Convert Between Fahrenheit and Celsius
        • 5. Check Whether an Object Is Empty
    • How the new Operator Works
    • ES5 Object-Oriented Programming
    • ES6 Object-Oriented Programming
    • Performance Comparison of Multiple Array Deduplication Methods
    • JS Randomly Shuffle an Array
    • Detect Whether the Browser Is on a Mobile Device
    • Convert a 1D Array into a 2D Array by Specified Length
    • Debounce and Throttle Functions
    • JS Get and Modify URL Parameters
    • More Accurate Type Checking Than the typeof Operator
    • 三级目录

  • 学习笔记

  • 前端
  • JavaScript文章
xugaoyi
2021-11-02
Contents

33 Extremely Useful JavaScript One-Liners

# 1. Date Handling

# 1. Check Whether a Date Is Valid

This method checks whether a given date is valid:

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");  // true
1
2
3

# 2. Calculate the Number of Days Between Two Dates

This method calculates the interval between two dates:

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

dayDif(new Date("2021-11-3"), new Date("2022-2-1"))  // 90
1
2
3

90 days until the new year~

# 3. Find the Day of the Year for a Given Date

This method determines which day of the year the given date falls on:

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

dayOfYear(new Date());   // 307
1
2
3

Over 300 days of 2021 have already passed~

# 4. Format Time

This method converts a date to the hour:minutes:seconds format:

const timeFromDate = date => date.toTimeString().slice(0, 8);

timeFromDate(new Date(2021, 11, 2, 12, 30, 0));  // 12:30:00
timeFromDate(new Date());  // returns the current time 09:00:00
1
2
3
4

# 2. String Handling

# 1. Capitalize the First Letter of a String

This method capitalizes the first letter of an English string:

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

capitalize("hello world")  // Hello world
1
2
3

# 2. Reverse a String

This method reverses a string and returns the result:

const reverse = str => str.split('').reverse().join('');

reverse('hello world');   // 'dlrow olleh'
1
2
3

# 3. Generate a Random String

This method generates a random string:

const randomString = () => Math.random().toString(36).slice(2);

randomString();
1
2
3

# 4. Truncate a String

This method truncates a string at a specified length:

const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;

truncateString('Hi, I should be truncated because I am too loooong!', 36)   // 'Hi, I should be truncated because...'
1
2
3

# 5. Strip HTML from a String

This method removes HTML elements from a string:

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

# 3. Array Handling

# 1. Remove Duplicates from an Array

This method removes duplicate items from an array:

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

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

# 2. Check Whether an Array Is Empty

This method checks whether an array is empty, returning a boolean:

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);  // true
1
2
3

# 3. Merge Two Arrays

You can use either of these two approaches to merge two arrays:

const merge = (a, b) => a.concat(b);

const merge = (a, b) => [...a, ...b];
1
2
3

# 4. Number Operations

# 1. Check Whether a Number Is Odd or Even

This method determines whether a number is odd or even:

const isEven = num => num % 2 === 0;

isEven(996);
1
2
3

# 2. Calculate the Average of a Set of Numbers

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

average(1, 2, 3, 4, 5);   // 3
1
2
3

# 3. Get a Random Integer Between Two Integers

This method returns a random integer within a given range:

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

random(1, 50);
1
2
3

# 4. Round a Number to a Specified Number of Decimal Places

This method rounds a number 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
1
2
3
4

# 5. Color Operations

# 1. Convert RGB to Hexadecimal

This method converts an RGB color value to its hexadecimal representation:

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255);  // '#ffffff'
1
2
3

# 2. Generate a Random Hexadecimal Color

This method generates a random hexadecimal color value:

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

randomHex();
1
2
3

# 6. Browser Operations

# 1. Copy Content to the Clipboard

This method uses navigator.clipboard.writeText to copy text to the clipboard:

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

copyToClipboard("Hello World");
1
2
3

# 2. Clear All Cookies

This method accesses document.cookie and clears all cookies stored by the page:

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

# 3. Get the Selected Text

This method retrieves the text the user has selected using the built-in getSelection property:

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

getSelectedText();
1
2
3

# 4. Detect Dark Mode

This method checks whether the current environment is in dark mode, returning a boolean:

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

console.log(isDarkMode)
1
2
3

# 5. Scroll to the Top of the Page

This method scrolls the page back to the top:

const goToTop = () => window.scrollTo(0, 0);

goToTop();
1
2
3

# 6. Check Whether the Current Tab Is Active

This method checks whether the current browser tab is active:

const isTabInView = () => !document.hidden;
1

# 7. Check Whether the Current Device Is an Apple Device

This method detects whether the current device is an Apple device:

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

isAppleDevice();
1
2
3

# 8. Check Whether the Page Has Been Scrolled to the Bottom

This method checks whether the page has been scrolled all the way to the bottom:

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

# 9. Redirect to a URL

This method redirects to a new URL:

const redirect = url => location.href = url

redirect("https://www.google.com/")
1
2
3

# 10. Open the Browser Print Dialog

This method opens the browser's print dialog:

const showPrintDialog = () => window.print()
1

# 7. Miscellaneous

# 1. Generate a Random Boolean

This method returns a random boolean. Using Math.random() to generate a number between 0 and 1, there is a 50/50 chance of getting true or false.

const randomBoolean = () => Math.random() >= 0.5;

randomBoolean();
1
2
3

# 2. Swap Variables

You can swap two variables without a third variable using the following syntax:

[foo, bar] = [bar, foo];
1

# 3. Get the Type of a Variable

This method retrieves the type of a variable:

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

trueTypeOf('');     // string
trueTypeOf(0);      // number
trueTypeOf();       // undefined
trueTypeOf(null);   // null
trueTypeOf({});     // object
trueTypeOf([]);     // array
trueTypeOf(0);      // number
trueTypeOf(() => {});  // function
1
2
3
4
5
6
7
8
9
10

# 4. Convert Between Fahrenheit and Celsius

These methods convert between Celsius and Fahrenheit:

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0
1
2
3
4
5
6
7
8

# 5. Check Whether an Object Is Empty

This method checks whether a JavaScript object is empty:

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
1

Author: CUGGZ Link: https://juejin.cn/post/7025771605422768159

Edit (opens new window)
#JavaScript
Last Updated: 2026/03/21, 12:14:36
How the new Operator Works

How the new Operator Works→

Recent Updates
01
How I Discovered Disposable Email — A True Story
06-12
02
Animations in Grid Layout
09-15
03
Renaming a Git Branch
08-11
More Articles >
Theme by VDone | Copyright © 2026-2026 Nikolay Tuzov | MIT License | Telegram
  • Auto
  • Light Mode
  • Dark Mode
  • Reading Mode