davila7--claude-code-templates
1 行
13 KiB
JSON
1 行
13 KiB
JSON
{"content": "---\nname: javascript-mastery\ndescription: \"Comprehensive JavaScript reference covering 33+ essential concepts every developer should know. From fundamentals like primitives and closures to advanced patterns like async/await and functional programming. Use when explaining JS concepts, debugging JavaScript issues, or teaching JavaScript fundamentals.\"\n---\n\n# 🧠 JavaScript Mastery\n\n> 33+ essential JavaScript concepts every developer should know, inspired by [33-js-concepts](https://github.com/leonardomso/33-js-concepts).\n\n## When to Use This Skill\n\nUse this skill when:\n\n- Explaining JavaScript concepts\n- Debugging tricky JS behavior\n- Teaching JavaScript fundamentals\n- Reviewing code for JS best practices\n- Understanding language quirks\n\n---\n\n## 1. Fundamentals\n\n### 1.1 Primitive Types\n\nJavaScript has 7 primitive types:\n\n```javascript\n// String\nconst str = \"hello\";\n\n// Number (integers and floats)\nconst num = 42;\nconst float = 3.14;\n\n// BigInt (for large integers)\nconst big = 9007199254740991n;\n\n// Boolean\nconst bool = true;\n\n// Undefined\nlet undef; // undefined\n\n// Null\nconst empty = null;\n\n// Symbol (unique identifiers)\nconst sym = Symbol(\"description\");\n```\n\n**Key points**:\n\n- Primitives are immutable\n- Passed by value\n- `typeof null === \"object\"` is a historical bug\n\n### 1.2 Type Coercion\n\nJavaScript implicitly converts types:\n\n```javascript\n// String coercion\n\"5\" + 3; // \"53\" (number → string)\n\"5\" - 3; // 2 (string → number)\n\n// Boolean coercion\nBoolean(\"\"); // false\nBoolean(\"hello\"); // true\nBoolean(0); // false\nBoolean([]); // true (!)\n\n// Equality coercion\n\"5\" == 5; // true (coerces)\n\"5\" === 5; // false (strict)\n```\n\n**Falsy values** (8 total):\n`false`, `0`, `-0`, `0n`, `\"\"`, `null`, `undefined`, `NaN`\n\n### 1.3 Equality Operators\n\n```javascript\n// == (loose equality) - coerces types\nnull == undefined; // true\n\"1\" == 1; // true\n\n// === (strict equality) - no coercion\nnull === undefined; // false\n\"1\" === 1; // false\n\n// Object.is() - handles edge cases\nObject.is(NaN, NaN); // true (NaN === NaN is false!)\nObject.is(-0, 0); // false (0 === -0 is true!)\n```\n\n**Rule**: Always use `===` unless you have a specific reason not to.\n\n---\n\n## 2. Scope & Closures\n\n### 2.1 Scope Types\n\n```javascript\n// Global scope\nvar globalVar = \"global\";\n\nfunction outer() {\n // Function scope\n var functionVar = \"function\";\n\n if (true) {\n // Block scope (let/const only)\n let blockVar = \"block\";\n const alsoBlock = \"block\";\n var notBlock = \"function\"; // var ignores blocks!\n }\n}\n```\n\n### 2.2 Closures\n\nA closure is a function that remembers its lexical scope:\n\n```javascript\nfunction createCounter() {\n let count = 0; // \"closed over\" variable\n\n return {\n increment() {\n return ++count;\n },\n decrement() {\n return --count;\n },\n getCount() {\n return count;\n },\n };\n}\n\nconst counter = createCounter();\ncounter.increment(); // 1\ncounter.increment(); // 2\ncounter.getCount(); // 2\n```\n\n**Common use cases**:\n\n- Data privacy (module pattern)\n- Function factories\n- Partial application\n- Memoization\n\n### 2.3 var vs let vs const\n\n```javascript\n// var - function scoped, hoisted, can redeclare\nvar x = 1;\nvar x = 2; // OK\n\n// let - block scoped, hoisted (TDZ), no redeclare\nlet y = 1;\n// let y = 2; // Error!\n\n// const - like let, but can't reassign\nconst z = 1;\n// z = 2; // Error!\n\n// BUT: const objects are mutable\nconst obj = { a: 1 };\nobj.a = 2; // OK\nobj.b = 3; // OK\n```\n\n---\n\n## 3. Functions & Execution\n\n### 3.1 Call Stack\n\n```javascript\nfunction first() {\n console.log(\"first start\");\n second();\n console.log(\"first end\");\n}\n\nfunction second() {\n console.log(\"second\");\n}\n\nfirst();\n// Output:\n// \"first start\"\n// \"second\"\n// \"first end\"\n```\n\nStack overflow example:\n\n```javascript\nfunction infinite() {\n infinite(); // No base case!\n}\ninfinite(); // RangeError: Maximum call stack size exceeded\n```\n\n### 3.2 Hoisting\n\n```javascript\n// Variable hoisting\nconsole.log(a); // undefined (hoisted, not initialized)\nvar a = 5;\n\nconsole.log(b); // ReferenceError (TDZ)\nlet b = 5;\n\n// Function hoisting\nsayHi(); // Works!\nfunction sayHi() {\n console.log(\"Hi!\");\n}\n\n// Function expressions don't hoist\nsayBye(); // TypeError\nvar sayBye = function () {\n console.log(\"Bye!\");\n};\n```\n\n### 3.3 this Keyword\n\n```javascript\n// Global context\nconsole.log(this); // window (browser) or global (Node)\n\n// Object method\nconst obj = {\n name: \"Alice\",\n greet() {\n console.log(this.name); // \"Alice\"\n },\n};\n\n// Arrow functions (lexical this)\nconst obj2 = {\n name: \"Bob\",\n greet: () => {\n console.log(this.name); // undefined (inherits outer this)\n },\n};\n\n// Explicit binding\nfunction greet() {\n console.log(this.name);\n}\ngreet.call({ name: \"Charlie\" }); // \"Charlie\"\ngreet.apply({ name: \"Diana\" }); // \"Diana\"\nconst bound = greet.bind({ name: \"Eve\" });\nbound(); // \"Eve\"\n```\n\n---\n\n## 4. Event Loop & Async\n\n### 4.1 Event Loop\n\n```javascript\nconsole.log(\"1\");\n\nsetTimeout(() => console.log(\"2\"), 0);\n\nPromise.resolve().then(() => console.log(\"3\"));\n\nconsole.log(\"4\");\n\n// Output: 1, 4, 3, 2\n// Why? Microtasks (Promises) run before macrotasks (setTimeout)\n```\n\n**Execution order**:\n\n1. Synchronous code (call stack)\n2. Microtasks (Promise callbacks, queueMicrotask)\n3. Macrotasks (setTimeout, setInterval, I/O)\n\n### 4.2 Callbacks\n\n```javascript\n// Callback pattern\nfunction fetchData(callback) {\n setTimeout(() => {\n callback(null, { data: \"result\" });\n }, 1000);\n}\n\n// Error-first convention\nfetchData((error, result) => {\n if (error) {\n console.error(error);\n return;\n }\n console.log(result);\n});\n\n// Callback hell (avoid this!)\ngetData((data) => {\n processData(data, (processed) => {\n saveData(processed, (saved) => {\n notify(saved, () => {\n // 😱 Pyramid of doom\n });\n });\n });\n});\n```\n\n### 4.3 Promises\n\n```javascript\n// Creating a Promise\nconst promise = new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve(\"Success!\");\n // or: reject(new Error(\"Failed!\"));\n }, 1000);\n});\n\n// Consuming Promises\npromise\n .then((result) => console.log(result))\n .catch((error) => console.error(error))\n .finally(() => console.log(\"Done\"));\n\n// Promise combinators\nPromise.all([p1, p2, p3]); // All must succeed\nPromise.allSettled([p1, p2]); // Wait for all, get status\nPromise.race([p1, p2]); // First to settle\nPromise.any([p1, p2]); // First to succeed\n```\n\n### 4.4 async/await\n\n```javascript\nasync function fetchUserData(userId) {\n try {\n const response = await fetch(`/api/users/${userId}`);\n if (!response.ok) throw new Error(\"Failed to fetch\");\n const user = await response.json();\n return user;\n } catch (error) {\n console.error(\"Error:\", error);\n throw error; // Re-throw for caller to handle\n }\n}\n\n// Parallel execution\nasync function fetchAll() {\n const [users, posts] = await Promise.all([\n fetch(\"/api/users\"),\n fetch(\"/api/posts\"),\n ]);\n return { users, posts };\n}\n```\n\n---\n\n## 5. Functional Programming\n\n### 5.1 Higher-Order Functions\n\nFunctions that take or return functions:\n\n```javascript\n// Takes a function\nconst numbers = [1, 2, 3];\nconst doubled = numbers.map((n) => n * 2); // [2, 4, 6]\n\n// Returns a function\nfunction multiply(a) {\n return function (b) {\n return a * b;\n };\n}\nconst double = multiply(2);\ndouble(5); // 10\n```\n\n### 5.2 Pure Functions\n\n```javascript\n// Pure: same input → same output, no side effects\nfunction add(a, b) {\n return a + b;\n}\n\n// Impure: modifies external state\nlet total = 0;\nfunction addToTotal(value) {\n total += value; // Side effect!\n return total;\n}\n\n// Impure: depends on external state\nfunction getDiscount(price) {\n return price * globalDiscountRate; // External dependency\n}\n```\n\n### 5.3 map, filter, reduce\n\n```javascript\nconst users = [\n { name: \"Alice\", age: 25 },\n { name: \"Bob\", age: 30 },\n { name: \"Charlie\", age: 35 },\n];\n\n// map: transform each element\nconst names = users.map((u) => u.name);\n// [\"Alice\", \"Bob\", \"Charlie\"]\n\n// filter: keep elements matching condition\nconst adults = users.filter((u) => u.age >= 30);\n// [{ name: \"Bob\", ... }, { name: \"Charlie\", ... }]\n\n// reduce: accumulate into single value\nconst totalAge = users.reduce((sum, u) => sum + u.age, 0);\n// 90\n\n// Chaining\nconst result = users\n .filter((u) => u.age >= 30)\n .map((u) => u.name)\n .join(\", \");\n// \"Bob, Charlie\"\n```\n\n### 5.4 Currying & Composition\n\n```javascript\n// Currying: transform f(a, b, c) into f(a)(b)(c)\nconst curry = (fn) => {\n return function curried(...args) {\n if (args.length >= fn.length) {\n return fn.apply(this, args);\n }\n return (...moreArgs) => curried(...args, ...moreArgs);\n };\n};\n\nconst add = curry((a, b, c) => a + b + c);\nadd(1)(2)(3); // 6\nadd(1, 2)(3); // 6\nadd(1)(2, 3); // 6\n\n// Composition: combine functions\nconst compose =\n (...fns) =>\n (x) =>\n fns.reduceRight((acc, fn) => fn(acc), x);\n\nconst pipe =\n (...fns) =>\n (x) =>\n fns.reduce((acc, fn) => fn(acc), x);\n\nconst addOne = (x) => x + 1;\nconst double = (x) => x * 2;\n\nconst addThenDouble = compose(double, addOne);\naddThenDouble(5); // 12 = (5 + 1) * 2\n\nconst doubleThenAdd = pipe(double, addOne);\ndoubleThenAdd(5); // 11 = (5 * 2) + 1\n```\n\n---\n\n## 6. Objects & Prototypes\n\n### 6.1 Prototypal Inheritance\n\n```javascript\n// Prototype chain\nconst animal = {\n speak() {\n console.log(\"Some sound\");\n },\n};\n\nconst dog = Object.create(animal);\ndog.bark = function () {\n console.log(\"Woof!\");\n};\n\ndog.speak(); // \"Some sound\" (inherited)\ndog.bark(); // \"Woof!\" (own method)\n\n// ES6 Classes (syntactic sugar)\nclass Animal {\n speak() {\n console.log(\"Some sound\");\n }\n}\n\nclass Dog extends Animal {\n bark() {\n console.log(\"Woof!\");\n }\n}\n```\n\n### 6.2 Object Methods\n\n```javascript\nconst obj = { a: 1, b: 2 };\n\n// Keys, values, entries\nObject.keys(obj); // [\"a\", \"b\"]\nObject.values(obj); // [1, 2]\nObject.entries(obj); // [[\"a\", 1], [\"b\", 2]]\n\n// Shallow copy\nconst copy = { ...obj };\nconst copy2 = Object.assign({}, obj);\n\n// Freeze (immutable)\nconst frozen = Object.freeze({ x: 1 });\nfrozen.x = 2; // Silently fails (or throws in strict mode)\n\n// Seal (no add/delete, can modify)\nconst sealed = Object.seal({ x: 1 });\nsealed.x = 2; // OK\nsealed.y = 3; // Fails\ndelete sealed.x; // Fails\n```\n\n---\n\n## 7. Modern JavaScript (ES6+)\n\n### 7.1 Destructuring\n\n```javascript\n// Array destructuring\nconst [first, second, ...rest] = [1, 2, 3, 4, 5];\n// first = 1, second = 2, rest = [3, 4, 5]\n\n// Object destructuring\nconst { name, age, city = \"Unknown\" } = { name: \"Alice\", age: 25 };\n// name = \"Alice\", age = 25, city = \"Unknown\"\n\n// Renaming\nconst { name: userName } = { name: \"Bob\" };\n// userName = \"Bob\"\n\n// Nested\nconst {\n address: { street },\n} = { address: { street: \"123 Main\" } };\n```\n\n### 7.2 Spread & Rest\n\n```javascript\n// Spread: expand iterable\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]\n\nconst obj1 = { a: 1 };\nconst obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }\n\n// Rest: collect remaining\nfunction sum(...numbers) {\n return numbers.reduce((a, b) => a + b, 0);\n}\nsum(1, 2, 3, 4); // 10\n```\n\n### 7.3 Modules\n\n```javascript\n// Named exports\nexport const PI = 3.14159;\nexport function square(x) {\n return x * x;\n}\n\n// Default export\nexport default class Calculator {}\n\n// Importing\nimport Calculator, { PI, square } from \"./math.js\";\nimport * as math from \"./math.js\";\n\n// Dynamic import\nconst module = await import(\"./dynamic.js\");\n```\n\n### 7.4 Optional Chaining & Nullish Coalescing\n\n```javascript\n// Optional chaining (?.)\nconst user = { address: { city: \"NYC\" } };\nconst city = user?.address?.city; // \"NYC\"\nconst zip = user?.address?.zip; // undefined (no error)\nconst fn = user?.getName?.(); // undefined if no method\n\n// Nullish coalescing (??)\nconst value = null ?? \"default\"; // \"default\"\nconst zero = 0 ?? \"default\"; // 0 (not nullish!)\nconst empty = \"\" ?? \"default\"; // \"\" (not nullish!)\n\n// Compare with ||\nconst value2 = 0 || \"default\"; // \"default\" (0 is falsy)\n```\n\n---\n\n## Quick Reference Card\n\n| Concept | Key Point |\n| :------------- | :-------------------------------- |\n| `==` vs `===` | Always use `===` |\n| `var` vs `let` | Prefer `let`/`const` |\n| Closures | Function + lexical scope |\n| `this` | Depends on how function is called |\n| Event loop | Microtasks before macrotasks |\n| Pure functions | Same input → same output |\n| Prototypes | `__proto__` → prototype chain |\n| `??` vs `\\|\\|` | `??` only checks null/undefined |\n\n---\n\n## Resources\n\n- [33 JS Concepts](https://github.com/leonardomso/33-js-concepts)\n- [JavaScript.info](https://javascript.info/)\n- [MDN JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)\n- [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS)\n"} |