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

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

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