28 JavaScript One-Liners Every Senior Developer Needs to Know
1. Swapping Values Without a Temporary Variable
let a = 1, b = 2;
[a, b] = [b, a];
// Output: a = 2, b = 1
2. Object Destructuring for Easier Data Access
const { name, age } = { name: 'John', age: 30 };
// Output: name = 'John', age = 30
3. Cloning Objects in a Snap
const originalObj = { name: 'Jane', age: 22 };
const clonedObj = { ...originalObj };
// Output: clonedObj = { name: 'Jane', age: 22 }
4. Merging Objects Made Simple
const obj1 = { name: 'Jane' };
const obj2 = { age: 22 };
const mergedObj = { ...obj1, ...obj2 };
// Output: mergedObj = { name: 'Jane', age: 22 }
5. Cleaning Up Arrays
const arr = [0, 1, false, 2, '', 3];
const cleanedArray = arr.filter(Boolean);
// Output: cleanedArray = [1, 2, 3]
6. Transforming NodeList to Array
const nodesArray = [...document.querySelectorAll('div')];
7. Checking Arrays for Specific Conditions
const arr = [1, 2, 3, -1, 4];
const hasNegativeNumbers = arr.some(num => num < 0);
// Output: hasNegativeNumbers = true
const allPositive = arr.every(num => num > 0);
// Output: allPositive = false
8. Copying Text to Clipboard
navigator.clipboard.writeText('Text to copy');
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]
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]
11. Sum of Array Values
const arr = [1, 2, 3, 4];
const sum = arr.reduce((total, value) => total + value, 0);
// Output: sum = 10
12. Conditional Object Property
const condition = true;
const value = 'Hello World';
const newObject = { ...(condition && { key: value }) };
// Output: newObject = { key: 'Hello World' }
13. Dynamic Object Key
const dynamicKey = 'name';
const value = 'John Doe';
const obj = { [dynamicKey]: value };
// Output: obj = { name: 'John Doe' }
14. Online Status Checker
const isOnline = navigator.onLine ? 'Online' : 'Offline';
// Output: isOnline = 'Online' or 'Offline'
15. Confirm Before Page Leave
window.onbeforeunload = () => 'Are you sure you want to leave?';
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
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' }
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'
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
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
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]
22. Safely Accessing Nested Object Properties
const user = { profile: { name: 'John Doe' } };
const userName = user.profile?.name ?? 'Anonymous';
// Output: userName = 'John Doe'
23. Conditional Execution
const isEligible = true;
isEligible && performAction();
// performAction is called if isEligible is true
24. Generating a Range of Numbers
const range = Array.from({ length: 5 }, (_, i) => i + 1);
// Output: range = [1, 2, 3, 4, 5]
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);
26. Extracting File Extension
const fileName = 'example.png';
const getFileExtension = str => str.slice(((str.lastIndexOf(".") - 1) >>> 0) + 2);
// Output: getFileExtension = 'png'
27. Checking if the Current Tab is Focused
const isTabFocused = () => document.hasFocus();
// Output: true (if the tab is focused), false otherwise
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');
These one-liners deliver impactful functionality in a concise manner, perfect for enhancing your JavaScript codebase.