Modern JS quick reference — 128+ snippets
Showing all snippets
let x = 10const PI = 3.14var old = truetypeof xArray.isArray(arr)Number('42')String(42)Boolean(0) // falseparseInt('42px') // 42parseFloat('3.14') // 3.14`Hello ${name}`str.lengthstr.toUpperCase()str.toLowerCase()str.trim()str.includes('sub')str.startsWith('pre')str.endsWith('.js')str.indexOf('sub')str.slice(1, 5)str.split(',')str.replace(/old/g, 'new')str.padStart(5, '0')str.repeat(3)[1, 2, 3]arr.push(4)arr.pop()arr.unshift(0)arr.shift()arr.lengtharr.includes(2)arr.indexOf(2)arr.find(x => x > 2)arr.findIndex(x => x > 2)arr.filter(x => x > 2)arr.map(x => x * 2)arr.reduce((sum, x) => sum + x, 0)arr.forEach(x => console.log(x))arr.some(x => x > 5)arr.every(x => x > 0)arr.sort((a, b) => a - b)arr.reverse()arr.flat()[...arr1, ...arr2]arr.slice(1, 3)arr.splice(1, 2)Array.from({length: 5}, (_, i) => i)[...new Set(arr)]{ key: 'value' }obj.keyobj['key']obj?.nested?.deepobj.key ?? 'default'Object.keys(obj)Object.values(obj)Object.entries(obj){ ...obj1, ...obj2 }const { a, b } = objconst { a: alias } = objconst { a = 10 } = objObject.assign({}, obj)structuredClone(obj)delete obj.key'key' in objObject.freeze(obj)function greet(name) {}const greet = (name) => {}const add = (a, b) => a + bfunction f(x = 10) {}function f(...args) {}f(...arr)const fn = (a, b = a * 2) => {}setTimeout(() => {}, 1000)setInterval(() => {}, 1000)new Promise((resolve, reject) => {})promise.then(val => {})promise.catch(err => {})promise.finally(() => {})async function f() {}const result = await promisePromise.all([p1, p2])Promise.allSettled([p1, p2])Promise.race([p1, p2])Promise.any([p1, p2])try { await f() } catch(e) {}document.getElementById('id')document.querySelector('.class')document.querySelectorAll('div')el.textContent = 'text'el.innerHTML = '<b>bold</b>'el.setAttribute('class', 'active')el.classList.add('active')el.classList.toggle('active')el.style.color = 'red'el.addEventListener('click', fn)el.remove()parent.appendChild(child)document.createElement('div')const res = await fetch(url)const data = await res.json()fetch(url, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } })res.okres.statusres.headers.get('content-type')const [a, b, ...rest] = [1,2,3,4]for (const item of arr) {}for (const [key, val] of map) {}new Map()new Set()Symbol('desc')class Dog { constructor(name) {} }class Puppy extends Dog {}export default function() {}import { func } from './module.js'import func from './module.js'a?.b?.ca ?? ba ||= ba ??= bMath.max(...arr)Math.min(...arr)Math.floor(Math.random() * 10)arr.sort(() => Math.random() - 0.5)JSON.parse(JSON.stringify(obj))new Date().toISOString()Number(n).toFixed(2)Object.fromEntries(entries)crypto.randomUUID()