7 JavaScript One-Liners that you should know
Today we will share the 7 useful JavaScript One-Liners that you should know.
Checkout more articles on JavaScript
- base64-in-javascript" title="Encode and decode strings with base64">Encode and decode strings with base64
- string-in-javascript" title="Remove all whitespace from a string in JavaScript">Remove all whitespace from a string in JavaScript
- Truncate string and add ellipsis in JavaScript
- Calculate age in years using JavaScript
7 JavaScript One-Liners
- Check if the current user has touch events supported
- Copy text to clipboard
- Reverse a string
- Check if the current tab is in view/focus
- Scroll to top of the page">Scroll to top of the page
- Generate a random string
- Check if the current user is on an Apple device
1. Check if the current user has touch events supported
Use the following function to check the touch support.
const isTouchSupported = () => ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
isTouchSupported(); // Output: true/false
// It will return true if touch events are supported, false if not.
2. Copy text to clipboard
Use the `navigator` to copy text to the clipboard.
Suggested article: How to copy text to the clipboard using JavaScript
const copyTextToClipboard = async text => await navigator.clipboard.writeText(text);
3. Reverse a string
Use the single line of code using `split()`, `reverse()` & `join()` methods to reverse a string.
const reverseStr = str => str.split('').reverse().join('');
reverseStr(“Clue Mediator”); // Output: rotaideM eulC
4. Check if the current tab is in view/focus
We can check if the current tab is in view/focus by using the `document.hidden` property.
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView(); // Output: true/false
// It’s returns true or false depending on if the tab is in view/focus.
5. Scroll to top of the page
Use the `window.scrollTo()` method to change the scroll position.
Suggested article: Animated sticky header on scroll using JavaScript
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
// It will scroll the browser to the top of the page.
6. Generate a random string
Using the `Math.random()`, we can generate a random string.
Suggested article: password-using-javascript" title="Generate a random password using JavaScript">Generate a random password using JavaScript
const getRandomStr = () => Math.random().toString(36).slice(2);
getRandomStr(); // Output: zgtgfqialz
7. Check if the current user is on an Apple device
We can use `navigator.platform` to check if the current user is on an Apple device.
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice); // Output: true/false
// It will return true if user is on an Apple device
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂