A Comprehensive Guide to Handy JavaScript One-Liners
Written on
Chapter 1: Introduction
Recently, I came across some intriguing articles about one-liners in JavaScript. Inspired by them, I decided to compile a collection to share with you. I trust this will prove beneficial in your coding endeavors. Although some of these methods may lack elegance, the primary goal of this article is to enhance your skills with various APIs.
Chapter 2: Date Operations
Validating a Date
This one-liner checks if a provided date is valid.
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 27, 2022 13:14:00"); // true
Calculating Date Intervals
Use this to find the difference between two dates.
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
dayDif(new Date("2022-08-27"), new Date("2022-12-25")); // 120
120 days until Christmas.
Finding the Day of the Year
This method reveals which day of the year a specific date falls on.
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 239
239 days have passed in 2022.
Time Formatting
Convert a date into an hh:mm:ss format.
const timeFromDate = date => date.toTimeString().slice(0, 8);
timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00
For the current time:
timeFromDate(new Date()); // now time 09:00:00
Chapter 3: String Manipulation
Capitalizing the First Letter
This method capitalizes the first character of a string.
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize("hello world"); // Hello world
Reversing a String
Use this to reverse a given string.
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
Generating a Random String
This method creates a random string.
const randomString = () => Math.random().toString(36).slice(2);
randomString();
String Truncation
Truncate a string to 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...'
Removing HTML from a String
This method strips HTML tags from a string.
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
Chapter 4: Array Processing
Removing Duplicates
This method eliminates duplicate items from an array.
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
Checking Array Emptiness
Determine if an array is empty.
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true
Merging Arrays
Combine two arrays using the following methods.
const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
Chapter 5: Numerical Operations
Odd or Even Check
This method determines if a number is odd or even.
const isEven = num => num % 2 === 0;
isEven(996);
Calculating the Average
Get 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
Generating a Random Integer
This method retrieves a random integer between two numbers.
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);
Rounding to Specific Digits
Round a number to a certain 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
Chapter 6: Color Manipulation
RGB to Hex Conversion
Convert RGB values to hexadecimal format.
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255); // '#ffffff'
Random Hexadecimal Color
Generate a random hexadecimal color value.
const randomHex = () => #${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")};
randomHex();
Chapter 7: Browser Operations
Copying Text to Clipboard
Copy text to the clipboard using this method.
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
Clearing Cookies
Remove all cookies stored on the web page.
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, =;expires=${new Date(0).toUTCString()};path=/));
Getting Selected Text
Retrieve the text selected by the user.
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
Checking Dark Mode
Determine if the current environment is using dark mode.
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log(isDarkMode);
Navigating to the Top of the Page
Return to the top of the page.
const goToTop = () => window.scrollTo(0, 0);
goToTop();
Tab Activity Check
Check if the current tab is active.
const isTabInView = () => !document.hidden;
Apple Device Detection
Determine if the current device is an Apple device.
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
Scroll Detection
Check if the page is scrolled to the bottom.
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
URL Redirection
Redirect to a specified URL.
const redirect = url => location.href = url;
Opening Print Dialog
Open the browser's print dialog.
const showPrintDialog = () => window.print();
Chapter 8: Additional Utilities
Random Boolean Value
Generate a random Boolean value.
const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();
Variable Swapping
Swap the values of two variables without a temporary variable.
[foo, bar] = [bar, foo];
Getting Variable Type
Retrieve 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
Temperature Conversion
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
Checking Object Emptiness
Verify if a JavaScript object is empty.
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
Feel free to follow me on Twitter, LinkedIn, and GitHub! Writing is my passion, and I take pleasure in helping and inspiring others. If you have any inquiries, don't hesitate to reach out!
For more content, visit PlainEnglish.io and subscribe to our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord!