How to Transform Array Elements
Use .map() to create a new array with transformed elements
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]How to Fetch Data from an API
Use async/await with fetch() for clean async code
async function fetchUser() {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
return data;
}How to Interpolate Strings
Use template literals for string interpolation
const name = 'World';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, World!"How to Select DOM Elements
Use querySelector() or querySelectorAll()
const element = document.querySelector('.my-class');
const allElements = document.querySelectorAll('.my-class');How to Destructure Objects
Use destructuring to extract object properties
const user = { name: 'Alice', age: 30, city: 'NYC' };
const { name, age } = user;
console.log(name, age); // "Alice" 30How to Format Dates
Use toLocaleDateString() or Intl.DateTimeFormat()
const date = new Date();
const formatted = date.toLocaleDateString('en-US');
console.log(formatted); // "12/31/2024"How to Filter Arrays
Use .filter() to create a new array with matching elements
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]How to Clone and Merge Objects
Use spread operator (...) to clone and merge objects
const user = { name: 'Alice', age: 30 };
const updatedUser = { ...user, age: 31 };
console.log(updatedUser); // { name: 'Alice', age: 31 }How to Reduce Arrays to Single Values
Use .reduce() to accumulate array values into a single result
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15How to Split and Join Strings
Use .split() to convert string to array, .join() to convert array to string
const text = 'hello-world-javascript';
const words = text.split('-');
console.log(words); // ['hello', 'world', 'javascript']
const rejoined = words.join(' ');
console.log(rejoined); // "hello world javascript"How to Copy and Merge Arrays
Use spread operator (...) to copy and concatenate arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]How to Run Multiple Promises Concurrently
Use Promise.all() to wait for multiple promises
const promises = [fetch(url1), fetch(url2), fetch(url3)];
const results = await Promise.all(promises);
console.log(results); // Array of all responsesHow to Create DOM Elements
Use createElement() and appendChild() or template literals
const div = document.createElement('div');
div.className = 'card';
div.textContent = 'Hello World';
document.body.appendChild(div);How to Iterate Over Object Properties
Use Object.entries() or Object.keys() to iterate
const user = { name: 'Alice', age: 30, city: 'NYC' };
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});How to Check if String Contains Substring
Use .includes() to check for substring presence
const text = 'Hello World';
const hasWorld = text.includes('World');
console.log(hasWorld); // trueHow to Find Array Element Index
Use .findIndex() to get index of matching element
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const index = users.findIndex(user => user.id === 2);
console.log(index); // 1How to Handle DOM Events
Use addEventListener() for event handling
const button = document.querySelector('button');
button.addEventListener('click', (event) => {
console.log('Button clicked!', event);
});How to Add Delays in Async Functions
Create a promise-based sleep function
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function delayed() {
console.log('Start');
await sleep(2000); // Wait 2 seconds
console.log('After 2 seconds');
}How to Remove Whitespace from Strings
Use .trim() to remove leading and trailing whitespace
const text = ' Hello World ';
const trimmed = text.trim();
console.log(trimmed); // "Hello World"How to Check Array Conditions
Use .some() to check if any element matches, .every() for all
const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some(n => n % 2 === 0);
const allPositive = numbers.every(n => n > 0);
console.log(hasEven, allPositive); // true trueHow to Safely Access Nested Properties
Use optional chaining (?.) to safely access nested properties
const user = { profile: { name: 'Alice' } };
const name = user?.profile?.name;
console.log(name); // "Alice"
const missing = user?.address?.city;
console.log(missing); // undefined (no error)How to Compare Dates
Convert dates to timestamps for comparison
const date1 = new Date('2024-01-01');
const date2 = new Date('2024-12-31');
const isAfter = date2 > date1;
console.log(isAfter); // trueHow to Manipulate CSS Classes
Use classList methods to add, remove, or toggle classes
const element = document.querySelector('.box');
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('visible');How to Flatten Nested Arrays
Use .flat() to flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
const flat = nested.flat();
console.log(flat); // [1, 2, 3, 4, [5, 6]]
const deepFlat = nested.flat(2);
console.log(deepFlat); // [1, 2, 3, 4, 5, 6]How to Replace Text in Strings
Use .replace() or .replaceAll() to substitute text
const text = 'Hello World';
const replaced = text.replace('World', 'JavaScript');
console.log(replaced); // "Hello JavaScript"How to Make Objects Immutable
Use Object.freeze() to make objects immutable
const config = Object.freeze({
apiUrl: 'https://api.example.com',
timeout: 5000
});
config.timeout = 3000; // Fails silently (or throws in strict mode)
console.log(config.timeout); // 5000How to Handle Async Errors
Use try/catch with async/await for error handling
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}How to Sort Arrays
Use .sort() with a compare function for proper sorting
const numbers = [10, 5, 40, 25, 1000];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(sorted); // [5, 10, 25, 40, 1000]How to Get Unique Values from Array
Use Set to remove duplicates from an array
const numbers = [1, 2, 2, 3, 3, 4, 5, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]How to Pad Strings
Use padStart() or padEnd() to add padding
const num = '5';
const padded = num.padStart(3, '0');
console.log(padded); // "005"How to Shallow Copy Objects
Use Object.assign() or spread operator for shallow copies
const original = { a: 1, b: 2 };
const copy1 = Object.assign({}, original);
const copy2 = { ...original };
console.log(copy2); // { a: 1, b: 2 }How to Work with Data Attributes
Use dataset property to access data-* attributes
const element = document.querySelector('.item');
const userId = element.dataset.userId;
element.dataset.status = 'active';How to Split Array into Chunks
Use slice in a loop to create array chunks
const chunk = (arr, size) => {
return Array.from(
{ length: Math.ceil(arr.length / size) },
(_, i) => arr.slice(i * size, i * size + size)
);
};
const chunked = chunk([1, 2, 3, 4, 5], 2);
console.log(chunked); // [[1, 2], [3, 4], [5]]How to Convert String Cases
Use case conversion methods and regex for different formats
const text = 'hello world';
const upper = text.toUpperCase(); // "HELLO WORLD"
const lower = text.toLowerCase(); // "hello world"How to Transform Object Keys
Use Object.entries() with reduce or fromEntries to transform keys
const obj = { first_name: 'John', last_name: 'Doe' };
const camelObj = Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k.replace(/_([a-z])/g, (_, c) => c.toUpperCase()), v]
)
);
console.log(camelObj); // { firstName: 'John', lastName: 'Doe' }How to Run Promises Sequentially
Use for...of loop with await to run promises in sequence
const urls = [url1, url2, url3];
const results = [];
for (const url of urls) {
const data = await fetch(url);
results.push(data);
}How to Handle Scrolling
Use scrollTo() and scroll events for scroll control
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });
// Scroll element into view
element.scrollIntoView({ behavior: 'smooth' });How to Group Array Items
Use reduce to group array items by property
const items = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'veg', name: 'carrot' }
];
const grouped = items.reduce((acc, item) => {
(acc[item.category] = acc[item.category] || []).push(item);
return acc;
}, {});How to Work with URL Parameters
Use URLSearchParams to parse and build query strings
const params = new URLSearchParams('?name=John&age=30');
console.log(params.get('name')); // "John"
params.append('city', 'NYC');
console.log(params.toString()); // "name=John&age=30&city=NYC"How to Pick or Omit Object Properties
Use destructuring and rest operator to pick/omit properties
const user = { id: 1, name: 'Alice', email: '[email protected]', password: '***' };
const { password, ...safe } = user;
console.log(safe); // { id: 1, name: 'Alice', email: '[email protected]' }How to Add/Subtract Time from Dates
Use setters or create new Date with modified timestamp
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow);How to Get Element Dimensions
Use getBoundingClientRect() for accurate dimensions
const element = document.querySelector('.box');
const rect = element.getBoundingClientRect();
console.log(rect.width, rect.height);How to Find Array Intersections
Use filter with includes to find common elements
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
const intersection = arr1.filter(x => arr2.includes(x));
console.log(intersection); // [3, 4]How to Truncate Strings
Use slice and add ellipsis for truncation
const text = 'This is a very long text';
const truncated = text.length > 20
? text.slice(0, 20) + '...'
: text;
console.log(truncated); // "This is a very long..."How to Create an Async Queue
Build a queue that processes async tasks with concurrency limit
class AsyncQueue {
constructor(concurrency = 1) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
}
async add(fn) {
while (this.running >= this.concurrency) {
await new Promise(resolve => this.queue.push(resolve));
}
this.running++;
try {
return await fn();
} finally {
this.running--;
this.queue.shift()?.();
}
}
}How to Deep Merge Objects
Recursively merge nested objects
function deepMerge(target, source) {
const output = { ...target };
for (const key in source) {
if (source[key] instanceof Object && key in target) {
output[key] = deepMerge(target[key], source[key]);
} else {
output[key] = source[key];
}
}
return output;
}How to Watch DOM Changes
Use MutationObserver to detect DOM modifications
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
console.log('DOM changed:', mutation.type);
});
});
observer.observe(element, {
childList: true,
subtree: true,
attributes: true
});How to Partition Arrays
Use reduce to split array into two groups based on condition
const numbers = [1, 2, 3, 4, 5, 6];
const [evens, odds] = numbers.reduce(
([pass, fail], num) =>
num % 2 === 0
? [[...pass, num], fail]
: [pass, [...fail, num]],
[[], []]
);
console.log(evens, odds); // [2, 4, 6] [1, 3, 5]How to Sanitize User Input
Escape HTML and remove dangerous characters
function escapeHTML(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
const safe = escapeHTML('<script>alert("xss")</script>');
console.log(safe); // "<script>alert("xss")</script>"