Code library
Free snippets & functions
Copy, adapt and use them in your own projects.
Beginner 270 snippets
const button = document.querySelector('#menu-btn');
const menu = document.querySelector('#menu');
button.addEventListener('click', () => {
const open = menu.classList.toggle('open');
button.setAttribute('aria-expanded', String(open));
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && menu.classList.contains('open')) {
menu.classList.remove('open');
button.setAttribute('aria-expanded', 'false');
button.focus();
}
});Toggle a class and keep aria-expanded in sync so screen readers know the state.
const params = new URLSearchParams(location.search); // ?page=2&q=php
const page = Number(params.get('page') ?? 1);
const q = params.get('q') ?? '';
const next = new URL(location.href);
next.searchParams.set('page', page + 1);
next.searchParams.delete('x');
const link = next.toString();
const query = new URLSearchParams({ q: 'a b&c', sort: 'new' }).toString(); // q=a+b%26c&sort=newURLSearchParams reads and writes query strings without manual splitting.
function toAge(value) {
const n = Number(value);
if (!Number.isInteger(n) || n < 0 || n > 120) {
throw new RangeError('Age must be a whole number from 0 to 120');
}
return n;
}
let message = '';
try {
toAge('abc');
} catch (err) {
message = err.message; // show this to the user
} finally {
// runs always
}Catch problems you can handle, throw clear errors for the rest.
const stock = new Map();
stock.set('pen', 10);
stock.set('book', 3);
stock.get('pen'); // 10
stock.has('lamp'); // false
stock.delete('book');
stock.size; // 1
for (const [item, qty] of stock) {
console.log(item, qty);
}
const asObject = Object.fromEntries(stock); // { pen: 10 }Use Map when keys are not plain strings, or when you add and delete keys often.
const tags = ['php', 'js', 'php', 'css', 'js'];
const unique = [...new Set(tags)]; // ['php', 'js', 'css']
const seen = new Set();
seen.add('a'); seen.add('a');
seen.has('a'); // true
seen.size; // 1A Set stores each value once.
const nums = [10, 9, 1, 100];
nums.slice().sort(); // [1, 10, 100, 9] (text order!)
const asc = nums.slice().sort((a, b) => a - b); // [1, 9, 10, 100]
const desc = nums.slice().sort((a, b) => b - a);
const people = [{ n: 'Sara', age: 25 }, { n: 'Ali', age: 30 }];
people.sort((a, b) => a.n.localeCompare(b.n)); // by name, language awaresort() compares as text by default, so 10 comes before 9. Give it a compare function.
const a = parseInt('42px', 10); // 42
const b = parseFloat('3.14abc'); // 3.14
const c = Number('12abc'); // NaN (strict)
const d = Number.isNaN(c); // true
(1234.5678).toFixed(2); // '1234.57' (a string!)
Math.round(2.5); // 3
Math.floor(-1.5); // -2
0.1 + 0.2 === 0.3; // false: use cents or toFixed for money
const money = Math.round(19.99 * 100); // 1999 centsForm values are strings. Convert them, and check the result before using it.
const s = ' Hello, World ';
const t = s.trim(); // 'Hello, World'
t.toUpperCase(); t.toLowerCase();
t.includes('World'); // true
t.startsWith('Hello'); // true
t.slice(0, 5); // 'Hello'
t.split(', '); // ['Hello', 'World']
t.replace('World', 'JS'); // first match only
t.replaceAll('l', 'L'); // every match
'5'.padStart(3, '0'); // '005'
'ab'.repeat(3); // 'ababab'Search, cut, split and clean text.
const d = new Date('2026-11-03T14:30:00Z');
d.getFullYear(); // 2026
d.getMonth(); // 10 (months start at 0!)
d.getDate(); // 3
const nice = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' }).format(d);
const iso = d.toISOString().slice(0, 10); // '2026-11-03'
const tomorrow = new Date(d);
tomorrow.setDate(d.getDate() + 1);The Date object plus Intl.DateTimeFormat covers most display needs without a library.
const user = { id: 1, name: 'Ali', tags: ['a', 'b'] };
const text = JSON.stringify(user); // '{"id":1,"name":"Ali","tags":["a","b"]}'
const pretty = JSON.stringify(user, null, 2); // indented, for reading
function safeParse(s, fallback = null) {
try { return JSON.parse(s); } catch { return fallback; }
}
const back = safeParse(text);
const bad = safeParse('{oops', {});Turn an object into text to send or store, and back again. Wrap parse in try/catch for outside data.
setTimeout(() => console.log('after 2 seconds'), 2000);
let seconds = 0;
const id = setInterval(() => {
seconds++;
console.log(seconds);
if (seconds === 5) {
clearInterval(id); // stop the timer
}
}, 1000);Run code later or repeatedly. Always keep the id so you can stop it.
const form = document.querySelector('#contact');
form.addEventListener('submit', (e) => {
e.preventDefault();
const data = new FormData(form);
const name = data.get('name');
const plain = Object.fromEntries(data); // { name: '...', email: '...' }
console.log(name, plain);
});Collects every named field. Handy for sending to fetch() or turning into an object.
const list = document.querySelector('#todos');
function addTodo(text) {
const li = document.createElement('li');
li.textContent = text; // safe even if text contains <b>
li.className = 'todo';
list.append(li);
}
addTodo('Buy milk');
addTodo('<b>not bold</b>');
list.firstElementChild.remove(); // remove the first oneBuild elements with createElement and add them with append. Use textContent for user text.
const box = document.querySelector('.box');
box.textContent = 'Hello'; // plain text (safe)
box.classList.add('active');
box.classList.remove('hidden');
box.classList.toggle('open'); // add if missing, remove if present
const isOpen = box.classList.contains('open');
box.setAttribute('data-id', '42');
box.style.color = 'green';
box.hidden = false;textContent is safe for text. classList adds, removes and toggles classes.
const btn = document.querySelector('#save');
btn.addEventListener('click', (e) => {
e.preventDefault(); // stop a link or form from doing its default action
btn.textContent = 'Saved';
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
console.log('closed');
}
});addEventListener is the standard way. The event object tells you what happened.
const title = document.querySelector('h1');
const byId = document.getElementById('menu');
const links = document.querySelectorAll('nav a'); // NodeList
links.forEach(a => console.log(a.href));
const list = [...links].map(a => a.textContent.trim()); // turn into a real array
const firstInside = byId?.querySelector('.active');querySelector returns the first match, querySelectorAll returns all of them.
const fruits = ['apple', 'banana', 'cherry'];
const seen = [];
for (let i = 0; i < fruits.length; i++) { seen.push(i + ':' + fruits[i]); }
for (const f of fruits) { seen.push(f.toUpperCase()); } // values
for (const [i, f] of fruits.entries()) { seen.push(`${i + 1}.${f}`); } // index + value
const user = { name: 'Ali', age: 30 };
for (const [key, value] of Object.entries(user)) { seen.push(key + '=' + value); }
fruits.forEach((f, i) => seen.push(f[0]));Pick the simplest loop for the job.
const user = { profile: { address: null }, count: 0 };
const city = user.profile?.address?.city; // undefined, no error
const phone = user.contact?.phone ?? 'not given'; // 'not given'
const n = user.count ?? 10; // 0 (not 10: 0 is a real value)
const bad = user.count || 10; // 10 (|| treats 0 as missing)
const fn = user.save?.(); // call only if it exists?. stops at null or undefined instead of throwing. ?? gives a default only for null or undefined.
function add(a, b = 0) { return a + b; } // declaration + default value
const addFn = function (a, b) { return a + b; }; // expression
const addArrow = (a, b) => a + b; // arrow, implicit return
const square = n => n * n; // one parameter: no brackets
const makeUser = name => ({ name }); // return an object: wrap it in ( )
const total = [1, 2, 3].map(square).reduce(add);Three ways to write the same thing. Arrow functions are short and do not have their own this.
const a = [1, 2];
const b = [...a, 3, 4]; // [1,2,3,4]
const base = { theme: 'light', lang: 'en' };
const mine = { ...base, lang: 'ur' }; // later keys win: lang = 'ur'
function sum(...numbers) { // rest: any number of arguments
return numbers.reduce((s, n) => s + n, 0);
}
console.log(Math.max(...b)); // spread into argumentsSpread copies or merges. Rest collects the remaining values.
const user = { id: 7, name: 'Ali', address: { city: 'Lahore' } };
const { name, role = 'guest', address: { city } } = user; // role gets a default
const { id: userId } = user; // rename
const [first, , third = 'none'] = ['a', 'b']; // skip one, default for third
function show({ name, age = 18 }) { // in function parameters
return `${name} (${age})`;
}Pull values out in one line, with defaults and new names.
const prices = [10, 25, 5, 40];
const doubled = prices.map(p => p * 2); // [20, 50, 10, 80]
const big = prices.filter(p => p > 9); // [10, 25, 40]
const first = prices.find(p => p > 20); // 25
const total = prices.reduce((sum, p) => sum + p, 0); // 80
console.log(prices.includes(5), prices.some(p => p > 30), prices.every(p => p > 1));The four array methods you will use every day. None of them changes the original array.
const name = 'Sara';
const items = 3;
const price = 19.5;
const msg = `Hello ${name}, you have ${items} item${items === 1 ? '' : 's'} (total ${(items * price).toFixed(2)}).`;
const html = `
<li class="item">
<b>${name}</b>
</li>`;Backticks allow variables, expressions and multi-line text.
const site = 'khurrambaig.com'; // cannot be re-assigned
let visits = 0; // can change
visits = visits + 1;
const user = { name: 'Ali' };
user.name = 'Ali Khan'; // allowed: the object changes, not the variable
if (true) {
let inside = 'only here'; // block scope
}
// console.log(inside); // ReferenceErrorUse const by default, let when the value changes, and avoid var.
-- all orders placed in October 2026
SELECT id, total, created_at
FROM orders
WHERE created_at >= '2026-10-01'
AND created_at < '2026-11-01';
-- the last 7 days
SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL 7 DAY;Use a start date and "before the next day" so the whole last day is included.
SET @page = 3;
SET @per = 2;
SELECT id, name
FROM products
ORDER BY id
LIMIT 2 OFFSET 4; -- (page - 1) * per_page = 4
SELECT COUNT(*) AS total_rows FROM products; -- to calculate the page countPage 3 with 2 rows per page skips 4 rows. Always sort so pages are stable.
DELETE FROM order_items WHERE order_id = 1; -- some rows, can use WHERE
TRUNCATE TABLE visits; -- all rows, AUTO_INCREMENT starts again, no WHEREDELETE removes chosen rows and can be rolled back. TRUNCATE empties the table fast and resets the counter.
CREATE TABLE pages (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(120) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO pages (title) VALUES ('Home');
UPDATE pages SET title = 'Home page' WHERE id = 1; -- updated_at changes by itselfLet the database set the dates so every insert and update is stamped.
SELECT name, 'customer' AS type FROM customers
UNION ALL
SELECT name, 'product' AS type FROM products
ORDER BY name;UNION removes duplicates. UNION ALL keeps them and is faster.
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid');EXISTS stops at the first match, so it is fast for "has any" questions.