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.
Add this skill
npx mdskills install sickn33/javascript-masteryComprehensive JavaScript reference with clear examples but lacks agent-specific triggers or step-by-step instructions
1---2name: javascript-mastery3description: "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."4---56# 🧠 JavaScript Mastery78> 33+ essential JavaScript concepts every developer should know, inspired by [33-js-concepts](https://github.com/leonardomso/33-js-concepts).910## When to Use This Skill1112Use this skill when:1314- Explaining JavaScript concepts15- Debugging tricky JS behavior16- Teaching JavaScript fundamentals17- Reviewing code for JS best practices18- Understanding language quirks1920---2122## 1. Fundamentals2324### 1.1 Primitive Types2526JavaScript has 7 primitive types:2728```javascript29// String30const str = "hello";3132// Number (integers and floats)33const num = 42;34const float = 3.14;3536// BigInt (for large integers)37const big = 9007199254740991n;3839// Boolean40const bool = true;4142// Undefined43let undef; // undefined4445// Null46const empty = null;4748// Symbol (unique identifiers)49const sym = Symbol("description");50```5152**Key points**:5354- Primitives are immutable55- Passed by value56- `typeof null === "object"` is a historical bug5758### 1.2 Type Coercion5960JavaScript implicitly converts types:6162```javascript63// String coercion64"5" + 3; // "53" (number → string)65"5" - 3; // 2 (string → number)6667// Boolean coercion68Boolean(""); // false69Boolean("hello"); // true70Boolean(0); // false71Boolean([]); // true (!)7273// Equality coercion74"5" == 5; // true (coerces)75"5" === 5; // false (strict)76```7778**Falsy values** (8 total):79`false`, `0`, `-0`, `0n`, `""`, `null`, `undefined`, `NaN`8081### 1.3 Equality Operators8283```javascript84// == (loose equality) - coerces types85null == undefined; // true86"1" == 1; // true8788// === (strict equality) - no coercion89null === undefined; // false90"1" === 1; // false9192// Object.is() - handles edge cases93Object.is(NaN, NaN); // true (NaN === NaN is false!)94Object.is(-0, 0); // false (0 === -0 is true!)95```9697**Rule**: Always use `===` unless you have a specific reason not to.9899---100101## 2. Scope & Closures102103### 2.1 Scope Types104105```javascript106// Global scope107var globalVar = "global";108109function outer() {110 // Function scope111 var functionVar = "function";112113 if (true) {114 // Block scope (let/const only)115 let blockVar = "block";116 const alsoBlock = "block";117 var notBlock = "function"; // var ignores blocks!118 }119}120```121122### 2.2 Closures123124A closure is a function that remembers its lexical scope:125126```javascript127function createCounter() {128 let count = 0; // "closed over" variable129130 return {131 increment() {132 return ++count;133 },134 decrement() {135 return --count;136 },137 getCount() {138 return count;139 },140 };141}142143const counter = createCounter();144counter.increment(); // 1145counter.increment(); // 2146counter.getCount(); // 2147```148149**Common use cases**:150151- Data privacy (module pattern)152- Function factories153- Partial application154- Memoization155156### 2.3 var vs let vs const157158```javascript159// var - function scoped, hoisted, can redeclare160var x = 1;161var x = 2; // OK162163// let - block scoped, hoisted (TDZ), no redeclare164let y = 1;165// let y = 2; // Error!166167// const - like let, but can't reassign168const z = 1;169// z = 2; // Error!170171// BUT: const objects are mutable172const obj = { a: 1 };173obj.a = 2; // OK174obj.b = 3; // OK175```176177---178179## 3. Functions & Execution180181### 3.1 Call Stack182183```javascript184function first() {185 console.log("first start");186 second();187 console.log("first end");188}189190function second() {191 console.log("second");192}193194first();195// Output:196// "first start"197// "second"198// "first end"199```200201Stack overflow example:202203```javascript204function infinite() {205 infinite(); // No base case!206}207infinite(); // RangeError: Maximum call stack size exceeded208```209210### 3.2 Hoisting211212```javascript213// Variable hoisting214console.log(a); // undefined (hoisted, not initialized)215var a = 5;216217console.log(b); // ReferenceError (TDZ)218let b = 5;219220// Function hoisting221sayHi(); // Works!222function sayHi() {223 console.log("Hi!");224}225226// Function expressions don't hoist227sayBye(); // TypeError228var sayBye = function () {229 console.log("Bye!");230};231```232233### 3.3 this Keyword234235```javascript236// Global context237console.log(this); // window (browser) or global (Node)238239// Object method240const obj = {241 name: "Alice",242 greet() {243 console.log(this.name); // "Alice"244 },245};246247// Arrow functions (lexical this)248const obj2 = {249 name: "Bob",250 greet: () => {251 console.log(this.name); // undefined (inherits outer this)252 },253};254255// Explicit binding256function greet() {257 console.log(this.name);258}259greet.call({ name: "Charlie" }); // "Charlie"260greet.apply({ name: "Diana" }); // "Diana"261const bound = greet.bind({ name: "Eve" });262bound(); // "Eve"263```264265---266267## 4. Event Loop & Async268269### 4.1 Event Loop270271```javascript272console.log("1");273274setTimeout(() => console.log("2"), 0);275276Promise.resolve().then(() => console.log("3"));277278console.log("4");279280// Output: 1, 4, 3, 2281// Why? Microtasks (Promises) run before macrotasks (setTimeout)282```283284**Execution order**:2852861. Synchronous code (call stack)2872. Microtasks (Promise callbacks, queueMicrotask)2883. Macrotasks (setTimeout, setInterval, I/O)289290### 4.2 Callbacks291292```javascript293// Callback pattern294function fetchData(callback) {295 setTimeout(() => {296 callback(null, { data: "result" });297 }, 1000);298}299300// Error-first convention301fetchData((error, result) => {302 if (error) {303 console.error(error);304 return;305 }306 console.log(result);307});308309// Callback hell (avoid this!)310getData((data) => {311 processData(data, (processed) => {312 saveData(processed, (saved) => {313 notify(saved, () => {314 // 😱 Pyramid of doom315 });316 });317 });318});319```320321### 4.3 Promises322323```javascript324// Creating a Promise325const promise = new Promise((resolve, reject) => {326 setTimeout(() => {327 resolve("Success!");328 // or: reject(new Error("Failed!"));329 }, 1000);330});331332// Consuming Promises333promise334 .then((result) => console.log(result))335 .catch((error) => console.error(error))336 .finally(() => console.log("Done"));337338// Promise combinators339Promise.all([p1, p2, p3]); // All must succeed340Promise.allSettled([p1, p2]); // Wait for all, get status341Promise.race([p1, p2]); // First to settle342Promise.any([p1, p2]); // First to succeed343```344345### 4.4 async/await346347```javascript348async function fetchUserData(userId) {349 try {350 const response = await fetch(`/api/users/${userId}`);351 if (!response.ok) throw new Error("Failed to fetch");352 const user = await response.json();353 return user;354 } catch (error) {355 console.error("Error:", error);356 throw error; // Re-throw for caller to handle357 }358}359360// Parallel execution361async function fetchAll() {362 const [users, posts] = await Promise.all([363 fetch("/api/users"),364 fetch("/api/posts"),365 ]);366 return { users, posts };367}368```369370---371372## 5. Functional Programming373374### 5.1 Higher-Order Functions375376Functions that take or return functions:377378```javascript379// Takes a function380const numbers = [1, 2, 3];381const doubled = numbers.map((n) => n * 2); // [2, 4, 6]382383// Returns a function384function multiply(a) {385 return function (b) {386 return a * b;387 };388}389const double = multiply(2);390double(5); // 10391```392393### 5.2 Pure Functions394395```javascript396// Pure: same input → same output, no side effects397function add(a, b) {398 return a + b;399}400401// Impure: modifies external state402let total = 0;403function addToTotal(value) {404 total += value; // Side effect!405 return total;406}407408// Impure: depends on external state409function getDiscount(price) {410 return price * globalDiscountRate; // External dependency411}412```413414### 5.3 map, filter, reduce415416```javascript417const users = [418 { name: "Alice", age: 25 },419 { name: "Bob", age: 30 },420 { name: "Charlie", age: 35 },421];422423// map: transform each element424const names = users.map((u) => u.name);425// ["Alice", "Bob", "Charlie"]426427// filter: keep elements matching condition428const adults = users.filter((u) => u.age >= 30);429// [{ name: "Bob", ... }, { name: "Charlie", ... }]430431// reduce: accumulate into single value432const totalAge = users.reduce((sum, u) => sum + u.age, 0);433// 90434435// Chaining436const result = users437 .filter((u) => u.age >= 30)438 .map((u) => u.name)439 .join(", ");440// "Bob, Charlie"441```442443### 5.4 Currying & Composition444445```javascript446// Currying: transform f(a, b, c) into f(a)(b)(c)447const curry = (fn) => {448 return function curried(...args) {449 if (args.length >= fn.length) {450 return fn.apply(this, args);451 }452 return (...moreArgs) => curried(...args, ...moreArgs);453 };454};455456const add = curry((a, b, c) => a + b + c);457add(1)(2)(3); // 6458add(1, 2)(3); // 6459add(1)(2, 3); // 6460461// Composition: combine functions462const compose =463 (...fns) =>464 (x) =>465 fns.reduceRight((acc, fn) => fn(acc), x);466467const pipe =468 (...fns) =>469 (x) =>470 fns.reduce((acc, fn) => fn(acc), x);471472const addOne = (x) => x + 1;473const double = (x) => x * 2;474475const addThenDouble = compose(double, addOne);476addThenDouble(5); // 12 = (5 + 1) * 2477478const doubleThenAdd = pipe(double, addOne);479doubleThenAdd(5); // 11 = (5 * 2) + 1480```481482---483484## 6. Objects & Prototypes485486### 6.1 Prototypal Inheritance487488```javascript489// Prototype chain490const animal = {491 speak() {492 console.log("Some sound");493 },494};495496const dog = Object.create(animal);497dog.bark = function () {498 console.log("Woof!");499};500501dog.speak(); // "Some sound" (inherited)502dog.bark(); // "Woof!" (own method)503504// ES6 Classes (syntactic sugar)505class Animal {506 speak() {507 console.log("Some sound");508 }509}510511class Dog extends Animal {512 bark() {513 console.log("Woof!");514 }515}516```517518### 6.2 Object Methods519520```javascript521const obj = { a: 1, b: 2 };522523// Keys, values, entries524Object.keys(obj); // ["a", "b"]525Object.values(obj); // [1, 2]526Object.entries(obj); // [["a", 1], ["b", 2]]527528// Shallow copy529const copy = { ...obj };530const copy2 = Object.assign({}, obj);531532// Freeze (immutable)533const frozen = Object.freeze({ x: 1 });534frozen.x = 2; // Silently fails (or throws in strict mode)535536// Seal (no add/delete, can modify)537const sealed = Object.seal({ x: 1 });538sealed.x = 2; // OK539sealed.y = 3; // Fails540delete sealed.x; // Fails541```542543---544545## 7. Modern JavaScript (ES6+)546547### 7.1 Destructuring548549```javascript550// Array destructuring551const [first, second, ...rest] = [1, 2, 3, 4, 5];552// first = 1, second = 2, rest = [3, 4, 5]553554// Object destructuring555const { name, age, city = "Unknown" } = { name: "Alice", age: 25 };556// name = "Alice", age = 25, city = "Unknown"557558// Renaming559const { name: userName } = { name: "Bob" };560// userName = "Bob"561562// Nested563const {564 address: { street },565} = { address: { street: "123 Main" } };566```567568### 7.2 Spread & Rest569570```javascript571// Spread: expand iterable572const arr1 = [1, 2, 3];573const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]574575const obj1 = { a: 1 };576const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }577578// Rest: collect remaining579function sum(...numbers) {580 return numbers.reduce((a, b) => a + b, 0);581}582sum(1, 2, 3, 4); // 10583```584585### 7.3 Modules586587```javascript588// Named exports589export const PI = 3.14159;590export function square(x) {591 return x * x;592}593594// Default export595export default class Calculator {}596597// Importing598import Calculator, { PI, square } from "./math.js";599import * as math from "./math.js";600601// Dynamic import602const module = await import("./dynamic.js");603```604605### 7.4 Optional Chaining & Nullish Coalescing606607```javascript608// Optional chaining (?.)609const user = { address: { city: "NYC" } };610const city = user?.address?.city; // "NYC"611const zip = user?.address?.zip; // undefined (no error)612const fn = user?.getName?.(); // undefined if no method613614// Nullish coalescing (??)615const value = null ?? "default"; // "default"616const zero = 0 ?? "default"; // 0 (not nullish!)617const empty = "" ?? "default"; // "" (not nullish!)618619// Compare with ||620const value2 = 0 || "default"; // "default" (0 is falsy)621```622623---624625## Quick Reference Card626627| Concept | Key Point |628| :------------- | :-------------------------------- |629| `==` vs `===` | Always use `===` |630| `var` vs `let` | Prefer `let`/`const` |631| Closures | Function + lexical scope |632| `this` | Depends on how function is called |633| Event loop | Microtasks before macrotasks |634| Pure functions | Same input → same output |635| Prototypes | `__proto__` → prototype chain |636| `??` vs `\|\|` | `??` only checks null/undefined |637638---639640## Resources641642- [33 JS Concepts](https://github.com/leonardomso/33-js-concepts)643- [JavaScript.info](https://javascript.info/)644- [MDN JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)645- [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS)646
Full transparency — inspect the skill content before installing.