0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
JavaScript · IntermediateSnippet

Object Destructuring with Aliasing and Defaults

Destructuring allows extracting object properties into variables with custom names (aliasing) and default values if the property is missing.

snippet.js
javascript
1
2
3
const config = { id: 101 };
const { id: userId, theme = 'dark' } = config;
console.log(userId, theme);
SyntaxData Types
JavaScript · IntermediateSnippet

Private State with Closures

A closure is created when an inner function references variables from its outer scope, allowing for private data encapsulation.

snippet.js
javascript
1
2
3
4
5
function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
FunctionsDesign Patterns
JavaScript · IntermediateSnippet

Resilient Parallel Async with Promise.allSettled

Unlike Promise.all, Promise.allSettled waits for all promises to finish regardless of whether they fulfilled or rejected.

snippet.js
javascript
1
2
3
const promises = [fetch('/api/1'), fetch('/api/2')];
const results = await Promise.allSettled(promises);
results.forEach(res => console.log(res.status));
Async & ConcurrencyError Handling
JavaScript · IntermediateSnippet

Optional Chaining and Nullish Coalescing

Optional chaining (?.) stops evaluation if the reference is nullish, while nullish coalescing (??) provides a default value only for null or undefined.

snippet.js
javascript
1
2
3
const user = { profile: { name: 'Alice' } };
const city = user.address?.city ?? 'Unknown';
console.log(city);
SyntaxBest Practices
JavaScript · IntermediateSnippet

Declarative Data Transformation

Chaining higher-order functions like filter and map allows for processing collections in a clean, readable, and declarative way.

snippet.js
javascript
1
2
3
4
const nums = [1, 2, 3, 4, 5];
const result = nums
.filter(n => n > 2)
.map(n => n * 2);
Arrays & ListsFunctions
JavaScript · IntermediateSnippet

Clean Async Cancellation with AbortController

The AbortController interface allows you to abort one or more Web requests as and when desired. This is essential for intermediate developers to handle component unmounting in frameworks or to prevent race conditions when multiple requests are triggered sequentially.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const controller = new AbortController();
const { signal } = controller;
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data', { signal });
return await response.json();
} catch (err) {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
}
}
}
fetchData();
controller.abort(); // Immediately cancels the fetch
Async & ConcurrencyBest Practices
JavaScript · IntermediateSnippet

Custom Iteration Logic with Generators

Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Using the '*' syntax and the 'yield' keyword, you can produce a sequence of values on demand, which is memory efficient for large datasets or custom sequences.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function* rangeGenerator(start, end, step = 1) {
let current = start;
while (current <= end) {
yield current;
current += step;
}
}
for (const num of rangeGenerator(0, 10, 2)) {
console.log(num); // 0, 2, 4, 6, 8, 10
}
SyntaxFunctions
JavaScript · IntermediateSnippet

Dynamic Data Validation with Proxies

The Proxy object allows you to create a wrapper for another object, which can intercept and redefine fundamental operations for that object, such as property lookup, assignment, and enumeration. In this intermediate example, we use the 'set' trap to implement real-time validation logic on an object's properties.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const userSchema = {
set(target, prop, value) {
if (prop === 'age') {
if (typeof value !== 'number' || value < 0) {
throw new Error('Age must be a positive number');
}
}
target[prop] = value;
return true;
}
};
const user = new Proxy({}, userSchema);
user.age = 25; // Works
// user.age = -5; // Throws Error
Design PatternsBest Practices