JavaScript Cheatsheet - ES6+ Command Reference
This reference serves developers building React/Vue, Node scripts, or any frontend project, focusing on the ES6+ syntax used daily: variables & functions, destructuring, template strings, higher-order array methods, async, and modules. Unlike docs that list APIs by name, entries here are grouped by the problem each snippet solves, so you can copy as you go. After reading you should be able to write block-scoped variables without var, pull values out with destructuring, replace handwritten for loops with map/filter, and tidy up callbacks with async/await.
Variables & Functions 6
const name = "value"let count = 0const fn = (x) => x * 2const fn = (x, y = 1) => {}const fn = (...args) => {}function* generator() { yield 1; }Destructuring 5
const [a, b] = [1, 2]const { name, age } = personconst { name: userName } = personconst [first, ...rest] = arrfunction fn({ name, age = 18 }) {}String & Template 6
`Hello ${name}`str.includes("text")str.startsWith("prefix")str.endsWith("suffix")str.padStart(10, "0")str.trim() / trimStart() / trimEnd()Array Methods 8
arr.map(x => x * 2)arr.filter(x => x > 0)arr.reduce((acc, x) => acc + x, 0)arr.find(x => x.id === 1)arr.findIndex(x => x > 0)arr.some(x => x > 0) / every(x => x > 0)arr.flat() / flatMap()Array.from(iterable) / Array.of(1,2,3)Async/Await 6
const p = new Promise((resolve, reject) => {})p.then(res => {}).catch(err => {})async function fn() { await p; }Promise.all([p1, p2])Promise.race([p1, p2])Promise.allSettled([p1, p2])Modules 6
import { name } from "./module.js"import * as utils from "./utils.js"import defaultExport from "./module.js"export const name = "value"export default function() {}export { name, age }Object & Class 6
const obj = { name, age }const obj = { fn() {} }const obj = { [`key${i}`]: value }Object.keys(obj) / values(obj) / entries(obj)class MyClass { constructor() {} }class Child extends Parent {}Typical Use Case
In React/Vue components you destructure fields out of props/state and build render text with template literals; in Node or SSR you chain file I/O and third-party requests with async/await; for client-side data processing you turn arrays into view-ready structures in one line with map/filter/reduce. Whether rewriting a modal, writing an API aggregator, or debugging an async race, the entry points used most are the array methods and async group.
Command Examples
Transform an array with map in one go
[1, 2, 3].map((x) => x * 2)map 返回一个长度相同的新数组,不改动原数组,适合派生视图数据。
Output
[2, 4, 6]
Destructure fields with a default value
const user = { name: "alice" }
const { name, age = 18 } = user
console.log(name, age)解构默认值只在属性值严格等于 undefined 时才生效,null 或空字符串不会被替换。
Output
alice 18
Await sequentially, then process
async function load() {
const res = await fetch("/api/user")
const data = await res.json()
return data
}await 会把后续逻辑暂挂到 Promise 落定后再继续,外层要用 try/catch 拦下 reject 的错误。
Run promises in parallel with Promise.all
const [a, b] = await Promise.all([p1, p2])Promise.all 有一个 reject 就整体 reject;想互不拖累地拿到各自结果用 Promise.allSettled。
Common Pitfalls
- Arrow functions do not bind their own this; use function when a dynamic this is needed in a method or event callback, or this leaks to the outer scope.
- const only prevents rebinding the variable itself — array push and object property assignment still work, so do not treat the value as frozen.
- Avoid var: it has function scope and hoisting, inviting ordering and closure-capture pitfalls; always use const/let.
- == performs implicit coercion (0 == false), so use === for equality; guard async throws inside try/catch so a reject does not become an unhandledrejection.
Tips
- Prefer const; only use let when reassignment is needed. Avoid var entirely.
- Arrow functions don't have their own this — they capture the surrounding context. Not suitable for object methods.
- async/await is syntactic sugar over Promises, making async code read like synchronous code.
FAQ
What exactly is the difference between == and === in JavaScript?
== coerces types before comparing, so '1' == 1 is true and null == undefined is true, which hides bugs; === requires both type and value to match with no coercion. Always use === in real code, and check empties with x === null or typeof.
When should I use var, let, and const?
var is function-scoped, redeclarable and hoisted, which causes surprises; let and const are block-scoped. Use const by default for values never reassigned, let when reassignment is needed, and avoid var entirely. Note that const only forbids reassignment — object properties stay mutable.
What is the difference between array map and forEach in JavaScript?
The key difference is the return value: map returns a new array built from each callback's return value, good for transformations; forEach just runs the callback and returns undefined, intended for side effects like printing or updating outside state. Use map to build a new array and forEach only to iterate.
How do I deep-copy an object safely in JavaScript?
Shallow copies ({...obj}, Object.assign) only duplicate the top level, so nested objects remain shared references. JSON.parse(JSON.stringify(obj)) deep-copies but drops functions, undefined, Date and RegExp and fails on circular references; use structuredClone(obj) when you must keep those or handle cycles.
How should I catch errors in async/await?
await re-throws a rejected promise as a normal exception, so wrap it in try/catch; at top level (e.g. module scope) use .catch(). A failed await does not automatically skip later lines — decide whether to fail the whole function or catch and continue.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us