20 Powerful JavaScript One‑Liners to Boost Your Coding Efficiency

Discover 20 concise JavaScript one‑line tricks—from array deduplication and variable swapping to debouncing and date calculations—that streamline common tasks, boost performance, and make your code more elegant, all explained with clear examples and brief explanations.

JavaScript
JavaScript
JavaScript
20 Powerful JavaScript One‑Liners to Boost Your Coding Efficiency

Master a collection of succinct and effective one‑line JavaScript techniques that can dramatically improve coding efficiency and make your code more elegant.

1. Array deduplication

const uniqueArray = [...new Set([1, 2, 3, 3, 4, 4, 5])]; // [1, 2, 3, 4, 5]

Use ES6's Set and the spread operator to easily remove duplicate values from an array, offering a cleaner and more efficient alternative to traditional looping methods.

2. Quick variable swap

[a, b] = [b, a];

Leverage array destructuring assignment to swap two values without a temporary variable, eliminating the classic three‑step swap process.

3. Check if an object is empty

const isEmpty = obj => Object.keys(obj).length === 0;

A one‑line arrow function that determines whether an object has any own enumerable properties, avoiding cumbersome property iteration.

4. Get a random element from an array

const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];

A concise method for selecting a random array element, ideal for lotteries, random displays, and similar scenarios.

5. Generate a random integer within a range

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

One line solves the need for a random integer between min and max, commonly used for mock data generation.

6. Convert RGB to hexadecimal color

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

Highly useful in front‑end color handling, this converts RGB values to a hex string quickly.

7. Copy text to clipboard

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

Modern browser APIs make copying text to the clipboard straightforward without third‑party libraries.

8. Detect device type

const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

Quickly determine whether the user is on a mobile device, aiding responsive experience implementation.

9. Smooth scroll to page top

const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });

Implement smooth scrolling back to the top of the page with a single line, enhancing user experience.

10. Retrieve URL query parameters

const getQueryParam = param => new URLSearchParams(window.location.search).get(param);

Utilize the built‑in URLSearchParams API to parse query strings effortlessly.

11. Calculate array average

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

Use reduce to compute the average of numeric array elements concisely and efficiently.

12. Check if an element is in the viewport

Useful for implementing lazy loading, infinite scrolling, and similar features.

13. Flatten an array

const flatten = arr => [].concat(...arr.map(item => Array.isArray(item) ? flatten(item) : item));

A recursive approach that transforms nested arrays into a single‑dimensional array.

14. Count occurrences of a value in an array

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

Counts how many times a specific element appears, handy for data‑analysis scenarios.

15. Generate a random hexadecimal color

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

Creates a random color string, useful when dynamic colors are needed.

16. Check if a date falls on a weekend

const isWeekend = date => [0, 6].includes(date.getDay());

Quickly determines whether a given date is Saturday or Sunday, applicable in calendar apps.

17. Calculate days between two dates

const daysBetween = (date1, date2) => Math.ceil(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));

Computes the number of days separating two dates, common in booking systems and countdown timers.

18. Capitalize the first letter of a string

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

A routine text‑formatting operation that ensures proper display of strings.

19. Shuffle an array (random sort)

const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);

Implements a simple random sort, suitable for card games, random displays, and similar use cases.

20. Debounce function

const debounce = (fn, delay) => { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => fn(...args), delay); }; };

Handles frequently triggered events such as input changes or window resizing, improving performance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptcode snippetsES6TipsOne-liners
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.