Kamilrashid.dev Full Stack Developer

Essential JavaScript One-Liners for Developers

1. Swapping Values Without a Temporary Variable

let a = 1, b = 2;
[a, b] = [b, a];
// Output: a = 2, b = 1

Array destructuring swaps a and b without a temporary variable, making the code cleaner.

2. Object Destructuring for Easier Data Access

const { name, age } = { name: 'John', age: 30 };
// Output: name = 'John', age = 30

Object destructuring extracts name and age properties into variables, enhancing readability.

3. Cloning Objects in a Snap

const originalObj = { name: 'Jane', age: 22 };
const clonedObj = { ...originalObj };
// Output: clonedObj = { name: 'Jane', age: 22 }

The spread operator creates a shallow clone of originalObj.

4. Merging Objects Made Simple

const obj1 = { name: 'Jane' };
const obj2 = { age: 22 };
const mergedObj = { ...obj1, ...obj2 };
// Output: mergedObj = { name: 'Jane', age: 22 }

Merge obj1 and obj2 using the spread operator.

5. Cleaning Up Arrays

const arr = [0, 1, false, 2, '', 3];
const cleanedArray = arr.filter(Boolean);
// Output: cleanedArray = [1, 2, 3]

Filter out falsy values using Array.prototype.filter() and the Boolean constructor.

6. Transforming NodeList to Array

javascript
Copy code
const nodesArray = [...document.querySelectorAll('div')];

Convert a NodeList to an array with the spread operator for easier manipulation.

7. Checking Arrays for Specific Conditions

const arr = [1, 2, 3, -1, 4];
const hasNegativeNumbers = arr.some(num => num < 0);
// Output: hasNegativeNumbers = true

Check if any elements are negative with .some().

8. Copying Text to Clipboard

javascript
Copy code
navigator.clipboard.writeText('Text to copy');

Use the Clipboard API to copy text programmatically.

9. Creating a Unique Array

const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(arr)];
// Output: unique = [1, 2, 3, 4, 5]

Remove duplicates by converting the array to a Set and back.

10. Finding the Intersection of Two Arrays

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4, 6, 8];
const intersection = arr1.filter(value => arr2.includes(value));
// Output: intersection = [2, 4]

Use Array.prototype.filter() to find common elements.

11. Sum of Array Values

const arr = [1, 2, 3, 4];
const sum = arr.reduce((total, value) => total + value, 0);
// Output: sum = 10

Sum array values with reduce.

12. Conditional Object Property

const condition = true;
const value = 'Hello World';
const newObject = { ...(condition && { key: value }) };
// Output: newObject = { key: 'Hello World' }

Conditionally add a property to an object using the spread operator and short-circuit evaluation.

13. Dynamic Object Key

const dynamicKey = 'name';
const value = 'John Doe';
const obj = { [dynamicKey]: value };
// Output: obj = { name: 'John Doe' }

Use computed property names to dynamically set object keys.

14. Online Status Checker

const isOnline = navigator.onLine ? 'Online' : 'Offline';
// Output: isOnline = 'Online' or 'Offline'

Check the browser’s online status using the ternary operator.

15. Confirm Before Page Leave

javascript
Copy code
window.onbeforeunload = () => 'Are you sure you want to leave?';

Trigger a confirmation dialog when the user tries to leave the page.

16. Sum of Object Values by Key

const arrayOfObjects = [{ x: 1 }, { x: 2 }, { x: 3 }];
const sumBy = (arr, key) => arr.reduce((acc, obj) => acc + obj[key], 0);
sumBy(arrayOfObjects, 'x');
// Output: 6

Sum values of a specific key across objects in an array.

17. Parse Query String to Object

const query = 'name=John&age=30';
const parseQuery = query => Object.fromEntries(new URLSearchParams(query));
// Output: parseQuery = { name: 'John', age: '30' }

Convert a query string to an object using URLSearchParams and Object.fromEntries.

18. Convert Seconds to Time String

const seconds = 3661;
const toTimeString = seconds => new Date(seconds * 1000).toISOString().substr(11, 8);
toTimeString(seconds);
// Output: '01:01:01'

Convert seconds into a HH:MM:SS format string.

19. Maximum Value in Object

const scores = { math: 95, science: 99, english: 88 };
const maxObjectValue = obj => Math.max(...Object.values(obj));
maxObjectValue(scores);
// Output: 99

Find the maximum value among an object’s values.

20. Check if Object Contains Value

const person = { name: 'John', age: 30 };
const hasValue = (obj, value) => Object.values(obj).includes(value);
hasValue(person, 30);
// Output: true

Check if a given value exists within an object’s values.

21. Boosting Scores Conditionally

const scores = [45, 75, 62, 55, 90];
const updatedScores = scores.map(score => score < 60 ? score + 20 : score);
// Output: updatedScores = [65, 75, 62, 75, 90]

Use the ternary operator within map to conditionally modify array elements.

22. Safely Accessing Nested Object Properties

const user = { profile: { name: 'John Doe' } };
const userName = user.profile?.name ?? 'Anonymous';
// Output: userName = 'John Doe'

Use optional chaining and nullish coalescing to safely access nested properties.

23. Conditional Execution

const isEligible = true;
isEligible && performAction();
// performAction is called if isEligible is true

Use the logical AND operator for concise conditional function execution.

24. Generating a Range of Numbers

const range = Array.from({ length: 5 }, (_, i) => i + 1);
// Output: range = [1, 2, 3, 4, 5]

Create a range of numbers using Array.from().

25. Implementing Promises with Timeout

const timeout = (promise, ms) => Promise.race([
  promise,
  new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), ms))
]);
timeout(fetch('https://api.example.com'), 5000).then(handleResponse).catch(handleError);

Create a timeout for a promise using Promise.race().

26. Extracting File Extension

const fileName = 'example.png';
const getFileExtension = str => str.slice(((str.lastIndexOf(".") - 1) >>> 0) + 2);
// Output: getFileExtension = 'png'

Extract the file extension from a string.

27. Checking if the Current Tab is Focused

const isTabFocused = () => document.hasFocus();
// Output: true (if the tab is focused), false otherwise

Check if the document has focus using document.hasFocus().

28. Toggling a Class Name on an Element

const element = document.querySelector('.my-element');
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(element, 'active');

Toggle a class on an element using classList.toggle().


These JavaScript one-liners deliver impactful functionality in a concise way, enhancing code efficiency and readability.