JavaScript Snippets

Modern solutions for everyday coding tasks

Showing 49 snippets
Arrays

How to Transform Array Elements

Use .map() to create a new array with transformed elements

javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
#map#array#transform
Async

How to Fetch Data from an API

Use async/await with fetch() for clean async code

javascript
async function fetchUser() {
  const response = await fetch('https://api.example.com/user');
  const data = await response.json();
  return data;
}
#async#fetch#api
Strings

How to Interpolate Strings

Use template literals for string interpolation

javascript
const name = 'World';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, World!"
#template-literals#strings#interpolation
DOM

How to Select DOM Elements

Use querySelector() or querySelectorAll()

javascript
const element = document.querySelector('.my-class');
const allElements = document.querySelectorAll('.my-class');
#dom#selector#query
Objects

How to Destructure Objects

Use destructuring to extract object properties

javascript
const user = { name: 'Alice', age: 30, city: 'NYC' };
const { name, age } = user;
console.log(name, age); // "Alice" 30
#destructuring#objects#es6
Dates

How to Format Dates

Use toLocaleDateString() or Intl.DateTimeFormat()

javascript
const date = new Date();
const formatted = date.toLocaleDateString('en-US');
console.log(formatted); // "12/31/2024"
#dates#formatting#intl
Arrays

How to Filter Arrays

Use .filter() to create a new array with matching elements

javascript
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
#filter#array#conditional
Objects

How to Clone and Merge Objects

Use spread operator (...) to clone and merge objects

javascript
const user = { name: 'Alice', age: 30 };
const updatedUser = { ...user, age: 31 };
console.log(updatedUser); // { name: 'Alice', age: 31 }
#spread#objects#clone
Arrays

How to Reduce Arrays to Single Values

Use .reduce() to accumulate array values into a single result

javascript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
#reduce#array#accumulate
Strings

How to Split and Join Strings

Use .split() to convert string to array, .join() to convert array to string

javascript
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"
#split#join#strings
Arrays

How to Copy and Merge Arrays

Use spread operator (...) to copy and concatenate arrays

javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
#spread#array#copy
Async

How to Run Multiple Promises Concurrently

Use Promise.all() to wait for multiple promises

javascript
const promises = [fetch(url1), fetch(url2), fetch(url3)];
const results = await Promise.all(promises);
console.log(results); // Array of all responses
#promise#async#concurrent
DOM

How to Create DOM Elements

Use createElement() and appendChild() or template literals

javascript
const div = document.createElement('div');
div.className = 'card';
div.textContent = 'Hello World';
document.body.appendChild(div);
#dom#create#element
Objects

How to Iterate Over Object Properties

Use Object.entries() or Object.keys() to iterate

javascript
const user = { name: 'Alice', age: 30, city: 'NYC' };
Object.entries(user).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
#objects#iterate#entries
Strings

How to Check if String Contains Substring

Use .includes() to check for substring presence

javascript
const text = 'Hello World';
const hasWorld = text.includes('World');
console.log(hasWorld); // true
#strings#includes#search
Arrays

How to Find Array Element Index

Use .findIndex() to get index of matching element

javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];
const index = users.findIndex(user => user.id === 2);
console.log(index); // 1
#array#find#index
DOM

How to Handle DOM Events

Use addEventListener() for event handling

javascript
const button = document.querySelector('button');
button.addEventListener('click', (event) => {
  console.log('Button clicked!', event);
});
#dom#events#listener
Async

How to Add Delays in Async Functions

Create a promise-based sleep function

javascript
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');
}
#async#delay#timeout
Strings

How to Remove Whitespace from Strings

Use .trim() to remove leading and trailing whitespace

javascript
const text = '  Hello World  ';
const trimmed = text.trim();
console.log(trimmed); // "Hello World"
#strings#trim#whitespace
Arrays

How to Check Array Conditions

Use .some() to check if any element matches, .every() for all

javascript
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 true
#array#some#every
Objects

How to Safely Access Nested Properties

Use optional chaining (?.) to safely access nested properties

javascript
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)
#objects#optional-chaining#safe-access
Dates

How to Compare Dates

Convert dates to timestamps for comparison

javascript
const date1 = new Date('2024-01-01');
const date2 = new Date('2024-12-31');
const isAfter = date2 > date1;
console.log(isAfter); // true
#dates#comparison#time
DOM

How to Manipulate CSS Classes

Use classList methods to add, remove, or toggle classes

javascript
const element = document.querySelector('.box');
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('visible');
#dom#classlist#css
Arrays

How to Flatten Nested Arrays

Use .flat() to flatten nested arrays

javascript
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]
#array#flat#flatten
Strings

How to Replace Text in Strings

Use .replace() or .replaceAll() to substitute text

javascript
const text = 'Hello World';
const replaced = text.replace('World', 'JavaScript');
console.log(replaced); // "Hello JavaScript"
#strings#replace#text
Objects

How to Make Objects Immutable

Use Object.freeze() to make objects immutable

javascript
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); // 5000
#objects#immutable#freeze
Async

How to Handle Async Errors

Use try/catch with async/await for error handling

javascript
async function fetchData() {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
#async#error-handling#try-catch
Arrays

How to Sort Arrays

Use .sort() with a compare function for proper sorting

javascript
const numbers = [10, 5, 40, 25, 1000];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(sorted); // [5, 10, 25, 40, 1000]
#array#sort#order
Arrays

How to Get Unique Values from Array

Use Set to remove duplicates from an array

javascript
const numbers = [1, 2, 2, 3, 3, 4, 5, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]
#array#unique#set
Strings

How to Pad Strings

Use padStart() or padEnd() to add padding

javascript
const num = '5';
const padded = num.padStart(3, '0');
console.log(padded); // "005"
#strings#pad#format
Objects

How to Shallow Copy Objects

Use Object.assign() or spread operator for shallow copies

javascript
const original = { a: 1, b: 2 };
const copy1 = Object.assign({}, original);
const copy2 = { ...original };
console.log(copy2); // { a: 1, b: 2 }
#objects#copy#assign
DOM

How to Work with Data Attributes

Use dataset property to access data-* attributes

javascript
const element = document.querySelector('.item');
const userId = element.dataset.userId;
element.dataset.status = 'active';
#dom#data-attributes#dataset
Arrays

How to Split Array into Chunks

Use slice in a loop to create array chunks

javascript
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]]
#array#chunk#split
Strings

How to Convert String Cases

Use case conversion methods and regex for different formats

javascript
const text = 'hello world';
const upper = text.toUpperCase(); // "HELLO WORLD"
const lower = text.toLowerCase(); // "hello world"
#strings#case#convert
Objects

How to Transform Object Keys

Use Object.entries() with reduce or fromEntries to transform keys

javascript
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' }
#objects#keys#transform
Async

How to Run Promises Sequentially

Use for...of loop with await to run promises in sequence

javascript
const urls = [url1, url2, url3];
const results = [];
for (const url of urls) {
  const data = await fetch(url);
  results.push(data);
}
#async#sequential#promises
DOM

How to Handle Scrolling

Use scrollTo() and scroll events for scroll control

javascript
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });

// Scroll element into view
element.scrollIntoView({ behavior: 'smooth' });
#dom#scroll#viewport
Arrays

How to Group Array Items

Use reduce to group array items by property

javascript
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;
}, {});
#array#group#categorize
Strings

How to Work with URL Parameters

Use URLSearchParams to parse and build query strings

javascript
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"
#strings#url#params
Objects

How to Pick or Omit Object Properties

Use destructuring and rest operator to pick/omit properties

javascript
const user = { id: 1, name: 'Alice', email: '[email protected]', password: '***' };
const { password, ...safe } = user;
console.log(safe); // { id: 1, name: 'Alice', email: '[email protected]' }
#objects#pick#omit
Dates

How to Add/Subtract Time from Dates

Use setters or create new Date with modified timestamp

javascript
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow);
#dates#add#subtract
DOM

How to Get Element Dimensions

Use getBoundingClientRect() for accurate dimensions

javascript
const element = document.querySelector('.box');
const rect = element.getBoundingClientRect();
console.log(rect.width, rect.height);
#dom#dimensions#size
Arrays

How to Find Array Intersections

Use filter with includes to find common elements

javascript
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]
#array#intersection#common
Strings

How to Truncate Strings

Use slice and add ellipsis for truncation

javascript
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..."
#strings#truncate#ellipsis
Async

How to Create an Async Queue

Build a queue that processes async tasks with concurrency limit

javascript
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()?.();
    }
  }
}
#async#queue#concurrency
Objects

How to Deep Merge Objects

Recursively merge nested objects

javascript
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;
}
#objects#merge#deep
DOM

How to Watch DOM Changes

Use MutationObserver to detect DOM modifications

javascript
const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    console.log('DOM changed:', mutation.type);
  });
});

observer.observe(element, {
  childList: true,
  subtree: true,
  attributes: true
});
#dom#observer#mutations
Arrays

How to Partition Arrays

Use reduce to split array into two groups based on condition

javascript
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]
#array#partition#split
Strings

How to Sanitize User Input

Escape HTML and remove dangerous characters

javascript
function escapeHTML(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

const safe = escapeHTML('<script>alert("xss")</script>');
console.log(safe); // "&lt;script&gt;alert("xss")&lt;/script&gt;"
#strings#sanitize#security