[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XRAR3K5CQQ0JRWQKVBYDR":3,"skill-same:01M72XRAR3K5CQQ0JRWQKVBYDR":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M72XRAR3K5CQQ0JRWQKVBYDR","modern-javascript-patterns",null,"Master ES6+ features including async\u002Fawait, destructuring, spread operators, arrow functions, promises, modules, iterators, generators, and functional programming patterns for writing clean, efficient JavaScript code. Use when refactoring legacy code, implementing modern patterns, or optimizing JavaScript applications.","steph-frtech\u002Fclaude-code-up","steph-frtech","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F198466323?v=4","01M72XD213FVQA2QXRGTJFKHE1","01M72XD227AANJ993SQTNZB1CK",1,"MIT","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fmodern-javascript-patterns\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: modern-javascript-patterns\ndescription: Master ES6+ features including async\u002Fawait, destructuring, spread operators, arrow functions, promises, modules, iterators, generators, and functional programming patterns for writing clean, efficient JavaScript code. Use when refactoring legacy code, implementing modern patterns, or optimizing JavaScript applications.\n---\n\n# Modern JavaScript Patterns\n\nComprehensive guide for mastering modern JavaScript (ES6+) features, functional programming patterns, and best practices for writing clean, maintainable, and performant code.\n\n## When to Use This Skill\n\n- Refactoring legacy JavaScript to modern syntax\n- Implementing functional programming patterns\n- Optimizing JavaScript performance\n- Writing maintainable and readable code\n- Working with asynchronous operations\n- Building modern web applications\n- Migrating from callbacks to Promises\u002Fasync-await\n- Implementing data transformation pipelines\n\n## ES6+ Core Features\n\n### 1. Arrow Functions\n\n**Syntax and Use Cases:**\n\n```javascript\n\u002F\u002F Traditional function\nfunction add(a, b) {\n  return a + b;\n}\n\n\u002F\u002F Arrow function\nconst add = (a, b) => a + b;\n\n\u002F\u002F Single parameter (parentheses optional)\nconst double = (x) => x * 2;\n\n\u002F\u002F No parameters\nconst getRandom = () => Math.random();\n\n\u002F\u002F Multiple statements (need curly braces)\nconst processUser = (user) => {\n  const normalized = user.name.toLowerCase();\n  return { ...user, name: normalized };\n};\n\n\u002F\u002F Returning objects (wrap in parentheses)\nconst createUser = (name, age) => ({ name, age });\n```\n\n**Lexical 'this' Binding:**\n\n```javascript\nclass Counter {\n  constructor() {\n    this.count = 0;\n  }\n\n  \u002F\u002F Arrow function preserves 'this' context\n  increment = () => {\n    this.count++;\n  };\n\n  \u002F\u002F Traditional function loses 'this' in callbacks\n  incrementTraditional() {\n    setTimeout(function () {\n      this.count++; \u002F\u002F 'this' is undefined\n    }, 1000);\n  }\n\n  \u002F\u002F Arrow function maintains 'this'\n  incrementArrow() {\n    setTimeout(() => {\n      this.count++; \u002F\u002F 'this' refers to Counter instance\n    }, 1000);\n  }\n}\n```\n\n### 2. Destructuring\n\n**Object Destructuring:**\n\n```javascript\nconst user = {\n  id: 1,\n  name: \"John Doe\",\n  email: \"john@example.com\",\n  address: {\n    city: \"New York\",\n    country: \"USA\",\n  },\n};\n\n\u002F\u002F Basic destructuring\nconst { name, email } = user;\n\n\u002F\u002F Rename variables\nconst { name: userName, email: userEmail } = user;\n\n\u002F\u002F Default values\nconst { age = 25 } = user;\n\n\u002F\u002F Nested destructuring\nconst {\n  address: { city, country },\n} = user;\n\n\u002F\u002F Rest operator\nconst { id, ...userWithoutId } = user;\n\n\u002F\u002F Function parameters\nfunction greet({ name, age = 18 }) {\n  console.log(`Hello ${name}, you are ${age}`);\n}\ngreet(user);\n```\n\n**Array Destructuring:**\n\n```javascript\nconst numbers = [1, 2, 3, 4, 5];\n\n\u002F\u002F Basic destructuring\nconst [first, second] = numbers;\n\n\u002F\u002F Skip elements\nconst [, , third] = numbers;\n\n\u002F\u002F Rest operator\nconst [head, ...tail] = numbers;\n\n\u002F\u002F Swapping variables\nlet a = 1,\n  b = 2;\n[a, b] = [b, a];\n\n\u002F\u002F Function return values\nfunction getCoordinates() {\n  return [10, 20];\n}\nconst [x, y] = getCoordinates();\n\n\u002F\u002F Default values\nconst [one, two, three = 0] = [1, 2];\n```\n\n### 3. Spread and Rest Operators\n\n**Spread Operator:**\n\n```javascript\n\u002F\u002F Array spreading\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\n\n\u002F\u002F Object spreading\nconst defaults = { theme: \"dark\", lang: \"en\" };\nconst userPrefs = { theme: \"light\" };\nconst settings = { ...defaults, ...userPrefs };\n\n\u002F\u002F Function arguments\nconst numbers = [1, 2, 3];\nMath.max(...numbers);\n\n\u002F\u002F Copying arrays\u002Fobjects (shallow copy)\nconst copy = [...arr1];\nconst objCopy = { ...user };\n\n\u002F\u002F Adding items immutably\nconst newArr = [...arr1, 4, 5];\nconst newObj = { ...user, age: 30 };\n```\n\n**Rest Parameters:**\n\n```javascript\n\u002F\u002F Collect function arguments\nfunction sum(...numbers) {\n  return numbers.reduce((total, num) => total + num, 0);\n}\nsum(1, 2, 3, 4, 5);\n\n\u002F\u002F With regular parameters\nfunction greet(greeting, ...names) {\n  return `${greeting} ${names.join(\", \")}`;\n}\ngreet(\"Hello\", \"John\", \"Jane\", \"Bob\");\n\n\u002F\u002F Object rest\nconst { id, ...userData } = user;\n\n\u002F\u002F Array rest\nconst [first, ...rest] = [1, 2, 3, 4, 5];\n```\n\n### 4. Template Literals\n\n```javascript\n\u002F\u002F Basic usage\nconst name = \"John\";\nconst greeting = `Hello, ${name}!`;\n\n\u002F\u002F Multi-line strings\nconst html = `\n  \u003Cdiv>\n    \u003Ch1>${title}\u003C\u002Fh1>\n    \u003Cp>${content}\u003C\u002Fp>\n  \u003C\u002Fdiv>\n`;\n\n\u002F\u002F Expression evaluation\nconst price = 19.99;\nconst total = `Total: $${(price * 1.2).toFixed(2)}`;\n\n\u002F\u002F Tagged template literals\nfunction highlight(strings, ...values) {\n  return strings.reduce((result, str, i) => {\n    const value = values[i] || \"\";\n    return result + str + `\u003Cmark>${value}\u003C\u002Fmark>`;\n  }, \"\");\n}\n\nconst name = \"John\";\nconst age = 30;\nconst html = highlight`Name: ${name}, Age: ${age}`;\n\u002F\u002F Output: \"Name: \u003Cmark>John\u003C\u002Fmark>, Age: \u003Cmark>30\u003C\u002Fmark>\"\n```\n\n### 5. Enhanced Object Literals\n\n```javascript\nconst name = \"John\";\nconst age = 30;\n\n\u002F\u002F Shorthand property names\nconst user = { name, age };\n\n\u002F\u002F Shorthand method names\nconst calculator = {\n  add(a, b) {\n    return a + b;\n  },\n  subtract(a, b) {\n    return a - b;\n  },\n};\n\n\u002F\u002F Computed property names\nconst field = \"email\";\nconst user = {\n  name: \"John\",\n  [field]: \"john@example.com\",\n  [`get${field.charAt(0).toUpperCase()}${field.slice(1)}`]() {\n    return this[field];\n  },\n};\n\n\u002F\u002F Dynamic property creation\nconst createUser = (name, ...props) => {\n  return props.reduce(\n    (user, [key, value]) => ({\n      ...user,\n      [key]: value,\n    }),\n    { name },\n  );\n};\n\nconst user = createUser(\"John\", [\"age\", 30], [\"email\", \"john@example.com\"]);\n```\n\n## Asynchronous Patterns\n\n### 1. Promises\n\n**Creating and Using Promises:**\n\n```javascript\n\u002F\u002F Creating a promise\nconst fetchUser = (id) => {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      if (id > 0) {\n        resolve({ id, name: \"John\" });\n      } else {\n        reject(new Error(\"Invalid ID\"));\n      }\n    }, 1000);\n  });\n};\n\n\u002F\u002F Using promises\nfetchUser(1)\n  .then((user) => console.log(user))\n  .catch((error) => console.error(error))\n  .finally(() => console.log(\"Done\"));\n\n\u002F\u002F Chaining promises\nfetchUser(1)\n  .then((user) => fetchUserPosts(user.id))\n  .then((posts) => processPosts(posts))\n  .then((result) => console.log(result))\n  .catch((error) => console.error(error));\n```\n\n**Promise Combinators:**\n\n```javascript\n\u002F\u002F Promise.all - Wait for all promises\nconst promises = [fetchUser(1), fetchUser(2), fetchUser(3)];\n\nPromise.all(promises)\n  .then((users) => console.log(users))\n  .catch((error) => console.error(\"At least one failed:\", error));\n\n\u002F\u002F Promise.allSettled - Wait for all, regardless of outcome\nPromise.allSettled(promises).then((results) => {\n  results.forEach((result) => {\n    if (result.status === \"fulfilled\") {\n      console.log(\"Success:\", result.value);\n    } else {\n      console.log(\"Error:\", result.reason);\n    }\n  });\n});\n\n\u002F\u002F Promise.race - First to complete\nPromise.race(promises)\n  .then((winner) => console.log(\"First:\", winner))\n  .catch((error) => console.error(error));\n\n\u002F\u002F Promise.any - First to succeed\nPromise.any(promises)\n  .then((first) => console.log(\"First success:\", first))\n  .catch((error) => console.error(\"All failed:\", error));\n```\n\n### 2. Async\u002FAwait\n\n**Basic Usage:**\n\n```javascript\n\u002F\u002F Async function always returns a Promise\nasync function fetchUser(id) {\n  const response = await fetch(`\u002Fapi\u002Fusers\u002F${id}`);\n  const user = await response.json();\n  return user;\n}\n\n\u002F\u002F Error handling with try\u002Fcatch\nasync function getUserData(id) {\n  try {\n    const user = await fetchUser(id);\n    const posts = await fetchUserPosts(user.id);\n    return { user, posts };\n  } catch (error) {\n    console.error(\"Error fetching data:\", error);\n    throw error;\n  }\n}\n\n\u002F\u002F Sequential vs Parallel execution\nasync function sequential() {\n  const user1 = await fetchUser(1); \u002F\u002F Wait\n  const user2 = await fetchUser(2); \u002F\u002F Then wait\n  return [user1, user2];\n}\n\nasync function parallel() {\n  const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);\n  return [user1, user2];\n}\n```\n\n**Advanced Patterns:**\n\n```javascript\n\u002F\u002F Async IIFE\n(async () => {\n  const result = await someAsyncOperation();\n  console.log(result);\n})();\n\n\u002F\u002F Async iteration\nasync function processUsers(userIds) {\n  for (const id of userIds) {\n    const user = await fetchUser(id);\n    await processUser(user);\n  }\n}\n\n\u002F\u002F Top-level await (ES2022)\nconst config = await fetch(\"\u002Fconfig.json\").then((r) => r.json());\n\n\u002F\u002F Retry logic\nasync function fetchWithRetry(url, retries = 3) {\n  for (let i = 0; i \u003C retries; i++) {\n    try {\n      return await fetch(url);\n    } catch (error) {\n      if (i === retries - 1) throw error;\n      await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));\n    }\n  }\n}\n\n\u002F\u002F Timeout wrapper\nasync function withTimeout(promise, ms) {\n  const timeout = new Promise((_, reject) =>\n    setTimeout(() => reject(new Error(\"Timeout\")), ms),\n  );\n  return Promise.race([promise, timeout]);\n}\n```\n\n## Functional Programming Patterns\n\nFunctional programming in JavaScript centers on pure functions, immutability, and composable transformations.\n\nKey topics covered in [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md):\n- **Array methods** — `map`, `filter`, `reduce`, `find`, `findIndex`, `some`, `every`, `flatMap`, `Array.from`\n- **Higher-order functions** — custom `forEach`\u002F`map`\u002F`filter`, currying, partial application, memoization\n- **Composition and piping** — `compose`\u002F`pipe` utilities with practical data transformation examples\n- **Pure functions and immutability** — immutable array\u002Fobject operations, deep cloning with `structuredClone`\n\n## Modern Class Features\n\nES2022 classes support private fields (`#field`), static fields, getters\u002Fsetters, and private methods. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md) for a full example with inheritance.\n\n## Modules (ES6)\n\n```javascript\n\u002F\u002F Named exports\nexport const PI = 3.14159;\nexport function add(a, b) { return a + b; }\n\n\u002F\u002F Default export\nexport default function multiply(a, b) { return a * b; }\n\n\u002F\u002F Import\nimport multiply, { PI, add } from \".\u002Fmath.js\";\n\n\u002F\u002F Dynamic import (code splitting)\nconst { add } = await import(\".\u002Fmath.js\");\n```\n\nFor re-exports, namespace imports, and conditional dynamic loading see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Iterators and Generators\n\nGenerators (`function*`) and async generators (`async function*`) enable lazy sequences and async pagination. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md) for custom iterator, range generator, fibonacci, and `for await...of` examples.\n\n## Modern Operators\n\n```javascript\n\u002F\u002F Optional chaining — safe property access\nconst city = user?.address?.city;\nconst result = obj.method?.();\n\n\u002F\u002F Nullish coalescing — default only for null\u002Fundefined (not 0 or \"\")\nconst value = null ?? \"default\"; \u002F\u002F 'default'\nconst zero = 0 ?? \"default\";    \u002F\u002F 0\n\n\u002F\u002F Logical assignment\na ??= \"default\";   \u002F\u002F assign if null\u002Fundefined\nobj.count ||= 1;   \u002F\u002F assign if falsy\nobj.count &&= 2;   \u002F\u002F assign if truthy\n```\n\n## Performance Optimization\n\nSee [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md) for debounce, throttle, and lazy evaluation with generators.\n\n## Best Practices\n\n1. **Use const by default**: Only use let when reassignment is needed\n2. **Prefer arrow functions**: Especially for callbacks\n3. **Use template literals**: Instead of string concatenation\n4. **Destructure objects and arrays**: For cleaner code\n5. **Use async\u002Fawait**: Instead of Promise chains\n6. **Avoid mutating data**: Use spread operator and array methods\n7. **Use optional chaining**: Prevent \"Cannot read property of undefined\"\n8. **Use nullish coalescing**: For default values\n9. **Prefer array methods**: Over traditional loops\n10. **Use modules**: For better code organization\n11. **Write pure functions**: Easier to test and reason about\n12. **Use meaningful variable names**: Self-documenting code\n13. **Keep functions small**: Single responsibility principle\n14. **Handle errors properly**: Use try\u002Fcatch with async\u002Fawait\n15. **Use strict mode**: `'use strict'` for better error catching\n\nFor common pitfalls (this binding, promise anti-patterns, memory leaks), see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n","# Modern JavaScript Patterns\n\nComprehensive guide for mastering modern JavaScript (ES6+) features, functional programming patterns, and best practices for writing clean, maintainable, and performant code.\n\n## When to Use This Skill\n\n- Refactoring legacy JavaScript to modern syntax\n- Implementing functional programming patterns\n- Optimizing JavaScript performance\n- Writing maintainable and readable code\n- Working with asynchronous operations\n- Building modern web applications\n- Migrating from callbacks to Promises\u002Fasync-await\n- Implementing data transformation pipelines\n\n## ES6+ Core Features\n\n### 1. Arrow Functions\n\n**Syntax and Use Cases:**\n\n```javascript\n\u002F\u002F Traditional function\nfunction add(a, b) {\n  return a + b;\n}\n\n\u002F\u002F Arrow function\nconst add = (a, b) => a + b;\n\n\u002F\u002F Single parameter (parentheses optional)\nconst double = (x) => x * 2;\n\n\u002F\u002F No parameters\nconst getRandom = () => Math.random();\n\n\u002F\u002F Multiple statements (need curly braces)\nconst processUser = (user) => {\n  const normalized = user.name.toLowerCase();\n  return { ...user, name: normalized };\n};\n\n\u002F\u002F Returning objects (wrap in parentheses)\nconst createUser = (name, age) => ({ name, age });\n```\n\n**Lexical 'this' Binding:**\n\n```javascript\nclass Counter {\n  constructor() {\n    this.count = 0;\n  }\n\n  \u002F\u002F Arrow function preserves 'this' context\n  increment = () => {\n    this.count++;\n  };\n\n  \u002F\u002F Traditional function loses 'this' in callbacks\n  incrementTraditional() {\n    setTimeout(function () {\n      this.count++; \u002F\u002F 'this' is undefined\n    }, 1000);\n  }\n\n  \u002F\u002F Arrow function maintains 'this'\n  incrementArrow() {\n    setTimeout(() => {\n      this.count++; \u002F\u002F 'this' refers to Counter instance\n    }, 1000);\n  }\n}\n```\n\n### 2. Destructuring\n\n**Object Destructuring:**\n\n```javascript\nconst user = {\n  id: 1,\n  name: \"John Doe\",\n  email: \"john@example.com\",\n  address: {\n    city: \"New York\",\n    country: \"USA\",\n  },\n};\n\n\u002F\u002F Basic destructuring\nconst { name, email } = user;\n\n\u002F\u002F Rename variables\nconst { name: userName, email: userEmail } = user;\n\n\u002F\u002F Default values\nconst { age = 25 } = user;\n\n\u002F\u002F Nested destructuring\nconst {\n  address: { city, country },\n} = user;\n\n\u002F\u002F Rest operator\nconst { id, ...userWithoutId } = user;\n\n\u002F\u002F Function parameters\nfunction greet({ name, age = 18 }) {\n  console.log(`Hello ${name}, you are ${age}`);\n}\ngreet(user);\n```\n\n**Array Destructuring:**\n\n```javascript\nconst numbers = [1, 2, 3, 4, 5];\n\n\u002F\u002F Basic destructuring\nconst [first, second] = numbers;\n\n\u002F\u002F Skip elements\nconst [, , third] = numbers;\n\n\u002F\u002F Rest operator\nconst [head, ...tail] = numbers;\n\n\u002F\u002F Swapping variables\nlet a = 1,\n  b = 2;\n[a, b] = [b, a];\n\n\u002F\u002F Function return values\nfunction getCoordinates() {\n  return [10, 20];\n}\nconst [x, y] = getCoordinates();\n\n\u002F\u002F Default values\nconst [one, two, three = 0] = [1, 2];\n```\n\n### 3. Spread and Rest Operators\n\n**Spread Operator:**\n\n```javascript\n\u002F\u002F Array spreading\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\n\n\u002F\u002F Object spreading\nconst defaults = { theme: \"dark\", lang: \"en\" };\nconst userPrefs = { theme: \"light\" };\nconst settings = { ...defaults, ...userPrefs };\n\n\u002F\u002F Function arguments\nconst numbers = [1, 2, 3];\nMath.max(...numbers);\n\n\u002F\u002F Copying arrays\u002Fobjects (shallow copy)\nconst copy = [...arr1];\nconst objCopy = { ...user };\n\n\u002F\u002F Adding items immutably\nconst newArr = [...arr1, 4, 5];\nconst newObj = { ...user, age: 30 };\n```\n\n**Rest Parameters:**\n\n```javascript\n\u002F\u002F Collect function arguments\nfunction sum(...numbers) {\n  return numbers.reduce((total, num) => total + num, 0);\n}\nsum(1, 2, 3, 4, 5);\n\n\u002F\u002F With regular parameters\nfunction greet(greeting, ...names) {\n  return `${greeting} ${names.join(\", \")}`;\n}\ngreet(\"Hello\", \"John\", \"Jane\", \"Bob\");\n\n\u002F\u002F Object rest\nconst { id, ...userData } = user;\n\n\u002F\u002F Array rest\nconst [first, ...rest] = [1, 2, 3, 4, 5];\n```\n\n### 4. Template Literals\n\n```javascript\n\u002F\u002F Basic usage\nconst name = \"John\";\nconst greeting = `Hello, ${name}!`;\n\n\u002F\u002F Multi-line strings\nconst html = `\n  \u003Cdiv>\n    \u003Ch1>${title}\u003C\u002Fh1>\n    \u003Cp>${content}\u003C\u002Fp>\n  \u003C\u002Fdiv>\n`;\n\n\u002F\u002F Expression evaluation\nconst price = 19.99;\nconst total = `Total: $${(price * 1.2).toFixed(2)}`;\n\n\u002F\u002F Tagged template literals\nfunction highlight(strings, ...values) {\n  return strings.reduce((result, str, i) => {\n    const value = values[i] || \"\";\n    return result + str + `\u003Cmark>${value}\u003C\u002Fmark>`;\n  }, \"\");\n}\n\nconst name = \"John\";\nconst age = 30;\nconst html = highlight`Name: ${name}, Age: ${age}`;\n\u002F\u002F Output: \"Name: \u003Cmark>John\u003C\u002Fmark>, Age: \u003Cmark>30\u003C\u002Fmark>\"\n```\n\n### 5. Enhanced Object Literals\n\n```javascript\nconst name = \"John\";\nconst age = 30;\n\n\u002F\u002F Shorthand property names\nconst user = { name, age };\n\n\u002F\u002F Shorthand method names\nconst calculator = {\n  add(a, b) {\n    return a + b;\n  },\n  subtract(a, b) {\n    return a - b;\n  },\n};\n\n\u002F\u002F Computed property names\nconst field = \"email\";\nconst user = {\n  name: \"John\",\n  [field]: \"john@example.com\",\n  [`get${field.charAt(0).toUpperCase()}${field.slice(1)}`]() {\n    return this[field];\n  },\n};\n\n\u002F\u002F Dynamic property creation\nconst createUser = (name, ...props) => {\n  return props.reduce(\n    (user, [key, value]) => ({\n      ...user,\n      [key]: value,\n    }),\n    { name },\n  );\n};\n\nconst user = createUser(\"John\", [\"age\", 30], [\"email\", \"john@example.com\"]);\n```\n\n## Asynchronous Patterns\n\n### 1. Promises\n\n**Creating and Using Promises:**\n\n```javascript\n\u002F\u002F Creating a promise\nconst fetchUser = (id) => {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      if (id > 0) {\n        resolve({ id, name: \"John\" });\n      } else {\n        reject(new Error(\"Invalid ID\"));\n      }\n    }, 1000);\n  });\n};\n\n\u002F\u002F Using promises\nfetchUser(1)\n  .then((user) => console.log(user))\n  .catch((error) => console.error(error))\n  .finally(() => console.log(\"Done\"));\n\n\u002F\u002F Chaining promises\nfetchUser(1)\n  .then((user) => fetchUserPosts(user.id))\n  .then((posts) => processPosts(posts))\n  .then((result) => console.log(result))\n  .catch((error) => console.error(error));\n```\n\n**Promise Combinators:**\n\n```javascript\n\u002F\u002F Promise.all - Wait for all promises\nconst promises = [fetchUser(1), fetchUser(2), fetchUser(3)];\n\nPromise.all(promises)\n  .then((users) => console.log(users))\n  .catch((error) => console.error(\"At least one failed:\", error));\n\n\u002F\u002F Promise.allSettled - Wait for all, regardless of outcome\nPromise.allSettled(promises).then((results) => {\n  results.forEach((result) => {\n    if (result.status === \"fulfilled\") {\n      console.log(\"Success:\", result.value);\n    } else {\n      console.log(\"Error:\", result.reason);\n    }\n  });\n});\n\n\u002F\u002F Promise.race - First to complete\nPromise.race(promises)\n  .then((winner) => console.log(\"First:\", winner))\n  .catch((error) => console.error(error));\n\n\u002F\u002F Promise.any - First to succeed\nPromise.any(promises)\n  .then((first) => console.log(\"First success:\", first))\n  .catch((error) => console.error(\"All failed:\", error));\n```\n\n### 2. Async\u002FAwait\n\n**Basic Usage:**\n\n```javascript\n\u002F\u002F Async function always returns a Promise\nasync function fetchUser(id) {\n  const response = await fetch(`\u002Fapi\u002Fusers\u002F${id}`);\n  const user = await response.json();\n  return user;\n}\n\n\u002F\u002F Error handling with try\u002Fcatch\nasync function getUserData(id) {\n  try {\n    const user = await fetchUser(id);\n    const posts = await fetchUserPosts(user.id);\n    return { user, posts };\n  } catch (error) {\n    console.error(\"Error fetching data:\", error);\n    throw error;\n  }\n}\n\n\u002F\u002F Sequential vs Parallel execution\nasync function sequential() {\n  const user1 = await fetchUser(1); \u002F\u002F Wait\n  const user2 = await fetchUser(2); \u002F\u002F Then wait\n  return [user1, user2];\n}\n\nasync function parallel() {\n  const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);\n  return [user1, user2];\n}\n```\n\n**Advanced Patterns:**\n\n```javascript\n\u002F\u002F Async IIFE\n(async () => {\n  const result = await someAsyncOperation();\n  console.log(result);\n})();\n\n\u002F\u002F Async iteration\nasync function processUsers(userIds) {\n  for (const id of userIds) {\n    const user = await fetchUser(id);\n    await processUser(user);\n  }\n}\n\n\u002F\u002F Top-level await (ES2022)\nconst config = await fetch(\"\u002Fconfig.json\").then((r) => r.json());\n\n\u002F\u002F Retry logic\nasync function fetchWithRetry(url, retries = 3) {\n  for (let i = 0; i \u003C retries; i++) {\n    try {\n      return await fetch(url);\n    } catch (error) {\n      if (i === retries - 1) throw error;\n      await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));\n    }\n  }\n}\n\n\u002F\u002F Timeout wrapper\nasync function withTimeout(promise, ms) {\n  const timeout = new Promise((_, reject) =>\n    setTimeout(() => reject(new Error(\"Timeout\")), ms),\n  );\n  return Promise.race([promise, timeout]);\n}\n```\n\n## Functional Programming Patterns\n\nFunctional programming in JavaScript centers on pure functions, immutability, and composable transformations.\n\nKey topics covered in [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md):\n- **Array methods** — `map`, `filter`, `reduce`, `find`, `findIndex`, `some`, `every`, `flatMap`, `Array.from`\n- **Higher-order functions** — custom `forEach`\u002F`map`\u002F`filter`, currying, partial application, memoization\n- **Composition and piping** — `compose`\u002F`pipe` utilities with practical data transformation examples\n- **Pure functions and immutability** — immutable array\u002Fobject operations, deep cloning with `structuredClone`\n\n## Modern Class Features\n\nES2022 classes support private fields (`#field`), static fields, getters\u002Fsetters, and private methods. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md) for a full example with inheritance.\n\n## Modules (ES6)\n\n```javascript\n\u002F\u002F Named exports\nexport const PI = 3.14159;\nexport function add(a, b) { return a + b; }\n\n\u002F\u002F Default export\nexport default function multiply(a, b) { return a * b; }\n\n\u002F\u002F Import\nimport multiply, { PI, add } from \".\u002Fmath.js\";\n\n\u002F\u002F Dynamic import (code splitting)\nconst { add } = await import(\".\u002Fmath.js\");\n```\n\nFor re-exports, namespace imports, and conditional dynamic loading see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n\n## Iterators and Generators\n\nGenerators (`function*`) and async generators (`async function*`) enable lazy sequences and async pagination. See [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md) for custom iterator, range generator, fibonacci, and `for await...of` examples.\n\n## Modern Operators\n\n```javascript\n\u002F\u002F Optional chaining — safe property access\nconst city = user?.address?.city;\nconst result = obj.method?.();\n\n\u002F\u002F Nullish coalescing — default only for null\u002Fundefined (not 0 or \"\")\nconst value = null ?? \"default\"; \u002F\u002F 'default'\nconst zero = 0 ?? \"default\";    \u002F\u002F 0\n\n\u002F\u002F Logical assignment\na ??= \"default\";   \u002F\u002F assign if null\u002Fundefined\nobj.count ||= 1;   \u002F\u002F assign if falsy\nobj.count &&= 2;   \u002F\u002F assign if truthy\n```\n\n## Performance Optimization\n\nSee [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md) for debounce, throttle, and lazy evaluation with generators.\n\n## Best Practices\n\n1. **Use const by default**: Only use let when reassignment is needed\n2. **Prefer arrow functions**: Especially for callbacks\n3. **Use template literals**: Instead of string concatenation\n4. **Destructure objects and arrays**: For cleaner code\n5. **Use async\u002Fawait**: Instead of Promise chains\n6. **Avoid mutating data**: Use spread operator and array methods\n7. **Use optional chaining**: Prevent \"Cannot read property of undefined\"\n8. **Use nullish coalescing**: For default values\n9. **Prefer array methods**: Over traditional loops\n10. **Use modules**: For better code organization\n11. **Write pure functions**: Easier to test and reason about\n12. **Use meaningful variable names**: Self-documenting code\n13. **Keep functions small**: Single responsibility principle\n14. **Handle errors properly**: Use try\u002Fcatch with async\u002Fawait\n15. **Use strict mode**: `'use strict'` for better error catching\n\nFor common pitfalls (this binding, promise anti-patterns, memory leaks), see [references\u002Fadvanced-patterns.md](references\u002Fadvanced-patterns.md).\n",{"name":5,"description":7},"main","900bb95bbe72cdb94af6f5a620aa5081264b7b6d",".claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fmodern-javascript-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up#readme","https:\u002F\u002Fgithub.com\u002Fsteph-frtech","2026-05-16 00:03:30",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add steph-frtech\u002Fclaude-code-up --skill modern-javascript-patterns",{"tool":37,"command":38},"bunx","bunx skills add steph-frtech\u002Fclaude-code-up --skill modern-javascript-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add steph-frtech\u002Fclaude-code-up --skill modern-javascript-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fmodern-javascript-patterns\u002FSKILL.md",true,[45],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"references\u002Fadvanced-patterns.md","REFERENCE","参考文档",10110,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fjavascript-typescript\u002Fskills\u002Fmodern-javascript-patterns\u002Freferences\u002Fadvanced-patterns.md",[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":18},"01M72Y1BY6X8TX3DS19Y04NEBQ","example","One-line summary of what this skill does","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002Fskills\u002Fexample\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":18},"01M72Y1A38EYR8S9P1MBYDAQTW","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__writing-plans\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M72Y174QSV1B5NV1E4KWHQBR","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M72Y14SQRHHMKG316HGB2CGK","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__test-driven-development\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M72Y127BCPRH3BRKPJC3Q3G2","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__systematic-debugging\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M72Y1090GJA6B67KPD60WPHH","subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__subagent-driven-development\u002FSKILL.md",[],[]]