javascript-mastery
33+ essential JavaScript concepts every developer should know, inspired by [33-js-concepts](https://github.com/leonardomso/33-js-concepts).
What this skill does
# ๐ง JavaScript Mastery
> 33+ essential JavaScript concepts every developer should know, inspired by [33-js-concepts](https://github.com/leonardomso/33-js-concepts).
## When to Use This Skill
Use this skill when:
- Explaining JavaScript concepts
- Debugging tricky JS behavior
- Teaching JavaScript fundamentals
- Reviewing code for JS best practices
- Understanding language quirks
---
## 1. Fundamentals
### 1.1 Primitive Types
JavaScript has 7 primitive types:
```javascript
// String
const str = "hello";
// Number (integers and floats)
const num = 42;
const float = 3.14;
// BigInt (for large integers)
const big = 9007199254740991n;
// Boolean
const bool = true;
// Undefined
let undef; // undefined
// Null
const empty = null;
// Symbol (unique identifiers)
const sym = Symbol("description");
```
**Key points**:
- Primitives are immutable
- Passed by value
- `typeof null === "object"` is a historical bug
### 1.2 Type Coercion
JavaScript implicitly converts types:
```javascript
// String coercion
"5" + 3; // "53" (number โ string)
"5" - 3; // 2 (string โ number)
// Boolean coercion
Boolean(""); // false
Boolean("hello"); // true
Boolean(0); // false
Boolean([]); // true (!)
// Equality coercion
"5" == 5; // true (coerces)
"5" === 5; // false (strict)
```
**Falsy values** (8 total):
`false`, `0`, `-0`, `0n`, `""`, `null`, `undefined`, `NaN`
### 1.3 Equality Operators
```javascript
// == (loose equality) - coerces types
null == undefined; // true
"1" == 1; // true
// === (strict equality) - no coercion
null === undefined; // false
"1" === 1; // false
// Object.is() - handles edge cases
Object.is(NaN, NaN); // true (NaN === NaN is false!)
Object.is(-0, 0); // false (0 === -0 is true!)
```
**Rule**: Always use `===` unless you have a specific reason not to.
---
## 2. Scope & Closures
### 2.1 Scope Types
```javascript
// Global scope
var globalVar = "global";
function outer() {
// Function scope
var functionVar = "function";
if (true) {
// Block scope (let/const only)
let blockVar = "block";
const alsoBlock = "block";
var notBlock = "function"; // var ignores blocks!
}
}
```
### 2.2 Closures
A closure is a function that remembers its lexical scope:
```javascript
function createCounter() {
let count = 0; // "closed over" variable
return {
increment() {
return ++count;
},
decrement() {
return --count;
},
getCount() {
return count;
},
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2
```
**Common use cases**:
- Data privacy (module pattern)
- Function factories
- Partial application
- Memoization
### 2.3 var vs let vs const
```javascript
// var - function scoped, hoisted, can redeclare
var x = 1;
var x = 2; // OK
// let - block scoped, hoisted (TDZ), no redeclare
let y = 1;
// let y = 2; // Error!
// const - like let, but can't reassign
const z = 1;
// z = 2; // Error!
// BUT: const objects are mutable
const obj = { a: 1 };
obj.a = 2; // OK
obj.b = 3; // OK
```
---
## 3. Functions & Execution
### 3.1 Call Stack
```javascript
function first() {
console.log("first start");
second();
console.log("first end");
}
function second() {
console.log("second");
}
first();
// Output:
// "first start"
// "second"
// "first end"
```
Stack overflow example:
```javascript
function infinite() {
infinite(); // No base case!
}
infinite(); // RangeError: Maximum call stack size exceeded
```
### 3.2 Hoisting
```javascript
// Variable hoisting
console.log(a); // undefined (hoisted, not initialized)
var a = 5;
console.log(b); // ReferenceError (TDZ)
let b = 5;
// Function hoisting
sayHi(); // Works!
function sayHi() {
console.log("Hi!");
}
// Function expressions don't hoist
sayBye(); // TypeError
var sayBye = function () {
console.log("Bye!");
};
```
### 3.3 this Keyword
```javascript
// Global context
console.log(this); // window (browser) or global (Node)
// Object method
const obj = {
name: "Alice",
greet() {
console.log(this.name); // "Alice"
},
};
// Arrow functions (lexical this)
const obj2 = {
name: "Bob",
greet: () => {
console.log(this.name); // undefined (inherits outer this)
},
};
// Explicit binding
function greet() {
console.log(this.name);
}
greet.call({ name: "Charlie" }); // "Charlie"
greet.apply({ name: "Diana" }); // "Diana"
const bound = greet.bind({ name: "Eve" });
bound(); // "Eve"
```
---
## 4. Event Loop & Async
### 4.1 Event Loop
```javascript
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2
// Why? Microtasks (Promises) run before macrotasks (setTimeout)
```
**Execution order**:
1. Synchronous code (call stack)
2. Microtasks (Promise callbacks, queueMicrotask)
3. Macrotasks (setTimeout, setInterval, I/O)
### 4.2 Callbacks
```javascript
// Callback pattern
function fetchData(callback) {
setTimeout(() => {
callback(null, { data: "result" });
}, 1000);
}
// Error-first convention
fetchData((error, result) => {
if (error) {
console.error(error);
return;
}
console.log(result);
});
// Callback hell (avoid this!)
getData((data) => {
processData(data, (processed) => {
saveData(processed, (saved) => {
notify(saved, () => {
// ๐ฑ Pyramid of doom
});
});
});
});
```
### 4.3 Promises
```javascript
// Creating a Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
// or: reject(new Error("Failed!"));
}, 1000);
});
// Consuming Promises
promise
.then((result) => console.log(result))
.catch((error) => console.error(error))
.finally(() => console.log("Done"));
// Promise combinators
Promise.all([p1, p2, p3]); // All must succeed
Promise.allSettled([p1, p2]); // Wait for all, get status
Promise.race([p1, p2]); // First to settle
Promise.any([p1, p2]); // First to succeed
```
### 4.4 async/await
```javascript
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error("Failed to fetch");
const user = await response.json();
return user;
} catch (error) {
console.error("Error:", error);
throw error; // Re-throw for caller to handle
}
}
// Parallel execution
async function fetchAll() {
const [users, posts] = await Promise.all([
fetch("/api/users"),
fetch("/api/posts"),
]);
return { users, posts };
}
```
---
## 5. Functional Programming
### 5.1 Higher-Order Functions
Functions that take or return functions:
```javascript
// Takes a function
const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2); // [2, 4, 6]
// Returns a function
function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2);
double(5); // 10
```
### 5.2 Pure Functions
```javascript
// Pure: same input โ same output, no side effects
function add(a, b) {
return a + b;
}
// Impure: modifies external state
let total = 0;
function addToTotal(value) {
total += value; // Side effect!
return total;
}
// Impure: depends on external state
function getDiscount(price) {
return price * globalDiscountRate; // External dependency
}
```
### 5.3 map, filter, reduce
```javascript
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 },
];
// map: transform each element
const names = users.map((u) => u.name);
// ["Alice", "Bob", "Charlie"]
// filter: keep elements matching condition
const adults = users.filter((u) => u.age >= 30);
// [{ name: "Bob", ... }, { name: "Charlie", ... }]
// reduce: accumulate into single value
const totalAge = users.reduce((sum, u) => sum + u.age, 0);
// 90
// Chaining
const result = users
.filter((u) => u.age >= 30)
.map((u) => u.name)
.join(", ");
// "Bob, Charlie"
```
### 5.4 Currying & ComRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.