diff --git a/README.md b/README.md index 924a02f7..3a7bf78f 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ IntroductionCommunityTable of Contents • + Modern TipsLicense

@@ -110,6 +111,7 @@ All the translations for this repo will be listed below: 31. [**Design Patterns**](#31-design-patterns) 32. [**Partial Applications, Currying, Compose and Pipe**](#32-partial-applications-currying-compose-and-pipe) 33. [**Clean Code**](#33-clean-code) +34. [**Modern JavaScript Tips**](#modern-tips)
@@ -1278,6 +1280,88 @@ The Event Loop is a critical part of JavaScript's concurrency model, ensuring no **[⬆ Back to Top](#table-of-contents)** +## Modern JavaScript Tips + +### 🚀 Additional Modern JavaScript Concepts + +Beyond the 33 fundamental concepts, here are some modern JavaScript tips and tricks that every developer should know: + +#### 1. **Optional Chaining (`?.`)** +```javascript +const user = { profile: { name: "John" } }; +const userName = user?.profile?.name; // Safe property access +``` + +#### 2. **Nullish Coalescing (`??`)** +```javascript +const theme = user?.preferences?.theme ?? 'light'; // Default for null/undefined +``` + +#### 3. **Template Literals with Tagged Templates** +```javascript +function highlight(strings, ...values) { + return strings.reduce((result, string, i) => { + return result + string + (values[i] ? `${values[i]}` : ''); + }, ''); +} +``` + +#### 4. **Destructuring with Default Values** +```javascript +const { name: userName = 'Anonymous', age = 0 } = user?.profile || {}; +``` + +#### 5. **Array Methods Chaining** +```javascript +const evenSquares = numbers + .filter(n => n % 2 === 0) + .map(n => n * n) + .reduce((sum, n) => sum + n, 0); +``` + +#### 6. **Dynamic Property Names** +```javascript +const prop = 'dynamic'; +const obj = { [prop]: 'value', [`${prop}Key`]: 'another value' }; +``` + +#### 7. **Async/Await with Error Handling** +```javascript +async function fetchUserData(id) { + try { + const response = await fetch(`/api/users/${id}`); + if (!response.ok) throw new Error('User not found'); + return await response.json(); + } catch (error) { + console.error('Error fetching user:', error.message); + return null; + } +} +``` + +#### 8. **Object.freeze() for Immutability** +```javascript +const config = Object.freeze({ apiUrl: 'https://api.example.com' }); +``` + +#### 9. **Set and Map for Better Data Structures** +```javascript +const uniqueIds = new Set([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4] +const userCache = new Map(); +``` + +#### 10. **Modern Array Methods** +```javascript +const hasActiveUsers = users.some(user => user.active); +const allUsersActive = users.every(user => user.active); +``` + +> 💡 **Pro Tip**: Check out the `index.js` file in this repository for practical examples of these modern JavaScript concepts! + +**[⬆ Back to Top](#table-of-contents)** + +--- + ## License This software is licensed under MIT License. See [License](https://github.com/leonardomso/33-js-concepts/blob/master/LICENSE) for more information ©Leonardo Maldonado. diff --git a/index.js b/index.js index 3d3b929b..1edf202f 100644 --- a/index.js +++ b/index.js @@ -5,3 +5,78 @@ Any kind of contribution is welcome. Feel free to contribute. */ + +// Modern JavaScript Tips & Tricks +// =============================== + +// 1. Optional Chaining (?.) - Safe property access +const user = { profile: { name: "John" } }; +const userName = user?.profile?.name; // "John" or undefined +const userAge = user?.profile?.age; // undefined (no error thrown) + +// 2. Nullish Coalescing (??) - Default values for null/undefined +const theme = user?.preferences?.theme ?? 'light'; // 'light' if null/undefined + +// 3. Template Literals with Tagged Templates +function highlight(strings, ...values) { + return strings.reduce((result, string, i) => { + return result + string + (values[i] ? `${values[i]}` : ''); + }, ''); +} +const name = "JavaScript"; +const message = highlight`Hello ${name}, welcome to modern JS!`; + +// 4. Destructuring with Default Values +const { name: userName = 'Anonymous', age = 0 } = user?.profile || {}; + +// 5. Array Methods Chaining +const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +const evenSquares = numbers + .filter(n => n % 2 === 0) + .map(n => n * n) + .reduce((sum, n) => sum + n, 0); + +// 6. Dynamic Property Names +const prop = 'dynamic'; +const obj = { + [prop]: 'value', + [`${prop}Key`]: 'another value' +}; + +// 7. Async/Await with Error Handling +async function fetchUserData(id) { + try { + const response = await fetch(`/api/users/${id}`); + if (!response.ok) throw new Error('User not found'); + return await response.json(); + } catch (error) { + console.error('Error fetching user:', error.message); + return null; + } +} + +// 8. Object.freeze() for Immutability +const config = Object.freeze({ + apiUrl: 'https://api.example.com', + timeout: 5000 +}); +// config.apiUrl = 'new-url'; // This will be ignored in strict mode + +// 9. Set and Map for Better Data Structures +const uniqueIds = new Set([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4] +const userCache = new Map(); +userCache.set('user1', { name: 'John', age: 30 }); + +// 10. Modern Array Methods +const users = [ + { id: 1, name: 'John', active: true }, + { id: 2, name: 'Jane', active: false }, + { id: 3, name: 'Bob', active: true } +]; + +const activeUsers = users.filter(user => user.active); +const userNames = users.map(user => user.name); +const hasActiveUsers = users.some(user => user.active); +const allUsersActive = users.every(user => user.active); + +console.log('Modern JavaScript Tips loaded successfully! 🚀');