17 Advanced JavaScript Tricks for Experienced Developers 🔥🔥
Certainly! Here are 20 advanced JavaScript tricks and techniques that can be useful for experienced developers:
- **Destructuring Assignment with Default Values:**
const { x = 0, y = 0 } = { x: 10 };
console.log(x, y); // Output: 10, 0
2. **Swapping Values with Destructuring:**
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // Output: 2, 1
3. **Using Spread Syntax for Object Merging:**
const obj1 = { x: 1, y: 2 };
const obj2 = { z: 3 };
const mergedObj = { …obj1, …obj2 };
console.log(mergedObj); // Output: { x: 1, y: 2, z: 3 }
4. **Array.flatMap() for Flattening and Mapping:**
const arr = [1, 2, 3];
const flattenedArr = arr.flatMap(x => [x, x * 2]);
console.log(flattenedArr); // Output: [1, 2, 2, 4, 3, 6]
5. **Optional Chaining (?.) Operator:**
const user = { name: 'John', address: { city: 'New York' } };
console.log(user?.address?.city); // Output: New York
6. **Nullish Coalescing (??) Operator:**
const name = null;
console.log(name ?? 'Anonymous'); // Output: Anonymous
7. **Memoization for Caching Function Results:**
const memoize = fn => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
return cache[key] || (cache[key] = fn(...args));
};
};
8. **Currying for Partial Function Application:**
const curry = (fn, arity = fn.length, …args) =>
arity <= args.length ? fn(…args) : curry.bind(null, fn, arity, …args);
9. **Private Class Fields with WeakMap:**
const privateProps = new WeakMap();
class Counter {
constructor() {
privateProps.set(this, { count: 0 });
}
increment() {
const props = privateProps.get(this);
props.count++;
return props.count;
}
}
10. **Using Proxy for Intercepting Object Operations:**
const handler = {
get: (target, prop) => (prop in target ? target[prop] : 'Not found')
};
const obj = new Proxy({ name: 'John' }, handler);
console.log(obj.name); // Output: John
console.log(obj.age); // Output: Not found
11. **Async/Await in Parallel with Promise.all():**
const fetchData = async () => {
const [result1, result2] = await Promise.all([fetchData1(), fetchData2()]);
// Process results
};
12. **Using IIFE (Immediately Invoked Function Expression):**
const result = (() => {
// Code block
return 'Result';
})();
13. **Function.prototype.bind() for Partial Application:**
const add = (x, y) => x + y;
const add5 = add.bind(null, 5);
console.log(add5(3)); // Output: 8
14. **Memoization with Memoize Libraries (e.g., lodash.memoize):**
const memoizedFn = _.memoize((x, y) => x * y);
console.log(memoizedFn(3, 4)); // Output: 12
15. **Using Object.freeze() for Immutable Objects:**
const obj = { prop: 'value' };
Object.freeze(obj);
16. **Using Map for Key-Value Data Structure:**
const map = new Map();
map.set('key', 'value');
console.log(map.get('key')); // Output: value
17. **Array.reduce() for Aggregating Values:**
const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10