Snippets
Reusable code snippets for Python, JavaScript, HTML, CSS, SQL, and more. Copy and use in your projects.
Unpack array values into named variables in one line тАФ swap values, skip items, and grab the rest.
const [first, second, ...rest] = [1, 2, 3, 4, 5]
// first=1, second=2, rest=[3,4,5]
// swap variables without a temp
[a, b] = [b, a]Build a new list from an iterable in a single readable line тАФ faster and more Pythonic than a for-loop.
squares = [x * x for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]Anonymous one-line functions perfect for short callbacks like sorting keys or quick transforms.
nums = [5, 2, 8, 1, 9]
nums.sort(key=lambda n: -n)
# [9, 8, 5, 2, 1]
# also useful with map/filter
doubled = list(map(lambda n: n * 2, nums))Format strings inline with expressions, numbers, and dates тАФ the cleanest way to build strings in Python 3.6+.
name = "Aarav"
score = 95.5
print(f"{name} scored {score:.1f}%")
# Aarav scored 95.5%Truly responsive grid without media queries тАФ columns automatically fit and reflow based on container width.
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1rem;
}Fire multiple async requests in parallel and wait for all of them тАФ dramatically faster than sequential awaits.
const urls = ["/api/a", "/api/b", "/api/c"]
const results = await Promise.all(
urls.map((u) => fetch(u).then((r) => r.json()))
)
// results = [dataA, dataB, dataC]Use semantic HTML5 landmarks for accessibility and SEO тАФ screen readers and search engines love them.
<body>
<header>тАжnavтАж</header>
<main>
<article>тАжpostтАж</article>
<aside>тАжrelatedтАж</aside>
</main>
<footer>тАжcopyrightтАж</footer>
</body>The classic "how do I center a div" тАФ solved in 3 lines with flexbox. Works horizontally and vertically.
.parent {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}Typed wrapper around localStorage that auto-parses JSON and silently catches quota / private-mode errors.
const store = {
get(key, fallback = null) {
try { return JSON.parse(localStorage.getItem(key)) ?? fallback }
catch { return fallback }
},
set(key, val) {
try { localStorage.setItem(key, JSON.stringify(val)) } catch {}
},
}Combine rows from two tables on a shared key тАФ INNER JOIN returns only matching rows from both sides.
SELECT u.name, COUNT(o.id) AS order_count
FROM users u
INNER JOIN orders o ON o.user_id = u.id
WHERE u.country = "India"
GROUP BY u.id
ORDER BY order_count DESC;