🚀 15 JavaScript Tricks I Wish Someone Had Taught Me Earlier
JavaScript is full of small features that can make your code cleaner, shorter, and easier to maintain. Here are 15 JavaScript tricks I use almost every week while building web applications with Next.js and React. Hopefully, you'll find at least a few that make your coding life easier. 1. Remove Duplicate Values const numbers = [ 1 , 2 , 2 , 3 , 4 , 4 , 5 ]; const unique = [... new Set ( numbers )]; console . log ( unique ); // [1,2,3,4,5] 2. Optional Chaining Instead of writing: if ( user && user . address && user . address . city ) { console . log ( user . address . city ); } Use: console . log ( user ?. address ?. city ); Much cleaner and safer. 3. Nullish Coalescing Operator const username = null ; console . log ( username ?? " Guest " ); Output: Guest Unlike || , this only replaces null or undefined . 4. Object Destructuring Instead of: const name = user . name ; const age = user . age ; Write: const { name , age } = user ; 5. Swap Variables Old way: let a = 10 ; let b = 20 ; const temp = a ; a = b ; b = temp ; Modern JavaScript: [ a , b ] = [ b , a ]; 6. Copy Objects const newUser = { ... user , }; No loops required. 7. Merge Objects const user = { name : " John " , }; const details = { age : 25 , }; const result = { ... user , ... details , }; console . log ( result ); 8. Remove Falsy Values const arr = [ 0 , "" , false , " Hello " , undefined , 5 , null ]; const clean = arr . filter ( Boolean ); console . log ( clean ); Output: [ "Hello" , 5 ] 9. Flatten Arrays const arr = [[ 1 ], [ 2 ], [ 3 ]]; console . log ( arr . flat ()); Output: [ 1 , 2 , 3 ] 10. Dynamic Property Names const key = " email " ; const user = { [ key ]: " john@example.com " , }; console . log ( user ); 11. Convert Object into Array const user = { name : " John " , age : 25 , }; console . log ( Object . entries ( user )); Output: [ [ " name " , " John " ], [ " age " , 25 ], ]; 12. Promise.all() Instead of waiting one request after another: await getUsers (); await getPosts (); await getComme