JavaScript code snippets with use cases
30 ready-made code building blocks, sorted by topic.
Basics
- Hello World β A first test that the browser console or Node works.
- Variables and types β Store values and check their type.
- Date and time β Calculate deadlines, format timestamps.
- Formatting numbers and dates (Intl) β Display prices, numbers and dates in the local style.
Data structures
- Working with arrays β Manage collections of values: add, sort, filter.
- Object as a dictionary β Store mappings, e.g. configurations or JSON-like data.
- Sorting by a custom criterion β Order records by a field, e.g. users by age or name.
- Removing duplicates & sets β Filter duplicate entries, form the intersection and union of two lists.
- Grouping data with reduce β Organize orders by customer, products by category or logs by level.
Advanced
- Destructuring in practice β Unpack nested API responses cleanly and set default values.
- Merging objects and arrays β Mix configurations with defaults without modifying the original.
- Optional chaining & nullish β Safely access deeply nested API data without a TypeError.
- Closure: private counter β Encapsulate state without using classes or global variables.
- Debounce for input β Send search requests only once the user has briefly stopped typing.
- Generator β Process large or infinite sequences piece by piece without holding everything in memory.
More snippets
- if / else if / else β React differently, e.g. calculate grades or price tiers.
- for and for...of loop β Process every element of a list or repeat n times.
- Function with default value β Bundle recurring logic, e.g. greeting texts or calculations.
- Class with inheritance β Bundle data and behavior, e.g. users, products, game characters.
- Class with a private field β Protect internal data, e.g. the balance or token of a class.
- try / catch / finally β Guard user input or network responses without the program crashing.
- Reading and writing a file (Node.js) β Save and load logs, configurations or text data.
- Reading and writing JSON β Exchange data with web APIs, localStorage or other programs.
- Counting words β Text analysis, e.g. most frequent words in a document.
- Regular expression β Find and reshape email addresses, dates or patterns in text.
- Loading data from an API (fetch) β Fetch data from a web API, e.g. weather, repositories or your own backends.
- Minimal HTTP server (Node.js) β Quickly provide a small API or a mock server for tests.
- Parallel tasks with Promise.all β Start several API calls at the same time and evaluate them together.
- DOM list with event delegation β Serve dynamic lists (to-dos, tables) with a single click handler.
- Storing data in the browser β Keep settings or to-do lists between page visits.