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.

Languages·43 commands·Last updated 2026-07-21

Typical Use Case

For developers writing browser and Node.js code. This sheet organises the language core by the parts you reach for most in real work: variables and functions, destructuring, strings, array methods, async, modules, and objects and classes. Three things deserve particular note: destructuring works directly in parameter position with defaults, the array methods map/filter/reduce cover the large majority of data processing, and Promise's all/race/allSettled have genuinely different semantics — picking the wrong one changes behaviour rather than just style.

Variables & Functions 6

const name = "value"
Declare constant, cannot be reassigned
let count = 0
Declare block-scoped variable
const fn = (x) => x * 2
Arrow function, single-line omits return
const fn = (x, y = 1) => {}
Default parameters
const fn = (...args) => {}
Rest parameters, collects all args into array
function* generator() { yield 1; }
Generator function

Destructuring 5

const [a, b] = [1, 2]
Array destructuring
const { name, age } = person
Object destructuring
const { name: userName } = person
Destructuring with rename
const [first, ...rest] = arr
Rest elements
function fn({ name, age = 18 }) {}
Function parameter destructuring

String & Template 6

`Hello ${name}`
Template literal with interpolation
str.includes("text")
Check if string contains substring
str.startsWith("prefix")
Check if string starts with prefix
str.endsWith("suffix")
Check if string ends with suffix
str.padStart(10, "0")
Pad start to specified length
str.trim() / trimStart() / trimEnd()
Remove whitespace

Array Methods 8

arr.map(x => x * 2)
Map each element, returns new array
arr.filter(x => x > 0)
Filter elements, returns new array
arr.reduce((acc, x) => acc + x, 0)
Reduce to a single value
arr.find(x => x.id === 1)
Find first matching element
arr.findIndex(x => x > 0)
Find first matching index
arr.some(x => x > 0) / every(x => x > 0)
Check if any / all match condition
arr.flat() / flatMap()
Flatten array
Array.from(iterable) / Array.of(1,2,3)
Create arrays

Async/Await 6

const p = new Promise((resolve, reject) => {})
Create a Promise
p.then(res => {}).catch(err => {})
Chaining
async function fn() { await p; }
async/await syntax
Promise.all([p1, p2])
Run in parallel, all must succeed
Promise.race([p1, p2])
Return the first settled
Promise.allSettled([p1, p2])
Wait for all, regardless of outcome

Modules 6

import { name } from "./module.js"
Named import
import * as utils from "./utils.js"
Import all as namespace
import defaultExport from "./module.js"
Default import
export const name = "value"
Named export
export default function() {}
Default export
export { name, age }
Export multiple

Object & Class 6

const obj = { name, age }
Property shorthand
const obj = { fn() {} }
Method shorthand
const obj = { [`key${i}`]: value }
Computed property names
Object.keys(obj) / values(obj) / entries(obj)
Get keys/values/entries
class MyClass { constructor() {} }
Class definition
class Child extends Parent {}
Class inheritance

Parameter matrix

ParameterEffectExample
const vs let不可重新赋值 / 可重新赋值,均为块级作用域const name = "value"
箭头函数省略 return,不绑定自己的 thisconst fn = (x) => x * 2
默认参数仅未传或显式传 undefined 时生效const fn = (x, y = 1) => {}
剩余参数 ...rest收集多余实参为真数组const fn = (...args) => {}
function* / yield生成器,惰性按需产出function* generator() { yield 1; }
数组解构 + 剩余取首项与剩余项const [first, ...rest] = arr
对象解构重命名属性名与变量名不一致时const { name: userName } = person
函数参数解构形参直接展开并可带默认值function fn({ name, age = 18 }) {}
模板字符串插值与多行`Hello ${name}`
map / filter / reduce映射 / 过滤 / 归约(均返回新值)arr.reduce((acc, x) => acc + x, 0)
find / findIndex找第一个元素 / 索引arr.find(x => x.id === 1)
some / every任一满足 / 全部满足(短路)arr.every(x => x > 0)
flat / flatMap扁平化数组arr.flat()
Promise.all / race / allSettled全成功 / 最先完成 / 等全部不论成败Promise.allSettled([p1, p2])
import / exportESM 具名与默认导出export const name = "value"

Common pitfalls

Symptom循环里用 var 定义变量,结果所有项都指向最后一个值。

Causevar 是函数作用域而非块级作用域,循环结束后仍共享同一个绑定。

Fix改用 let 或 const 获得块级作用域。

Symptom把箭头函数当对象方法,this 指向了外层而非对象。

Cause箭头函数没有自己的 this,会捕获定义时的 this。

Fix对象方法用 function 简写形式,需要调用对象自身时保留 this。

SymptomforEach 里用 async 函数,循环却没等异步完成。

CauseforEach 不等待回调返回的 Promise。

Fix改用 for...of 配合 await,或先 Promise.all 映射后再 await。

Symptom用 Promise.all 时因一个失败导致全部结果丢失。

Causeall 遇到任一 reject 立即 reject,不返回其他已完成的结果。

Fix需要保留各自结果时改用 Promise.allSettled。

Symptom默认参数没生效,值变成了 undefined。

Cause显式传了 null 不会触发默认值,只有不传或传 undefined 才触发。

Fix用 `x = 1` 形参,或在函数体内用 x ?? 1 处理 null。

Symptomconst 声明的数组 push 报错。

Cause误解了 const 语义:它锁定的是引用而非内容。

Fixconst 数组可以 push(内容可变),只是不能重新赋值给别的数组;要冻结内容用 Object.freeze。

Symptomreduce 不给初始值时结果变成 NaN 或抛错。

Cause空数组时 reduce 会拿第一个元素当初始值,之后运算出错。

Fix始终传第二个参数作为初始值,如 reduce((acc, x) => acc + x, 0)。

SymptomESM 引入的模块在 Node 里报 Unexpected token export。

Causepackage.json 未声明 "type": "module",Node 按 CommonJS 解析。

Fix设置 "type": "module",或把文件扩展名改为 .mjs;构建产物则交给打包器处理。

Troubleshooting

  1. 1确认 this 到底指向谁

    const fn = function() { console.log(this) }

    与箭头函数对照跑一次即可看出差别;对象方法必须用普通函数。

  2. 2循环内正确等待异步

    for (const x of list) { await handle(x) }

    for...of 会逐个 await;forEach 不会等,这是最常见的踩坑点。

  3. 3需要保留每个结果时改用 allSettled

    Promise.allSettled([p1, p2])

    返回每项的 status 与原因,适合批量任务部分失败仍要继续。

  4. 4安全地取可能缺失的键

    const { name = "匿名", age } = person

    解构默认值只在属性为 undefined 时生效,不影响 null。

  5. 5reduce 务必带初始值

    arr.reduce((acc, x) => acc + x, 0)

    空数组时不给初始值会出错;显式写 0 最安全。

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