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 letCannot be reassigned / can be reassigned, both block-scopedconst name = "value"
Arrow functionOmits return, does not bind its own thisconst fn = (x) => x * 2
Default parametersTakes effect only when not passed or explicitly passed undefinedconst fn = (x, y = 1) => {}
Rest parameters ...restCollects extra arguments into a real arrayconst fn = (...args) => {}
function* / yieldGenerator, produces values lazily on demandfunction* generator() { yield 1; }
Array destructuring + restTake the first item and the remaining itemsconst [first, ...rest] = arr
Object destructuring renameWhen the property name and variable name differconst { name: userName } = person
Function parameter destructuringParameters are expanded directly and can carry defaultsfunction fn({ name, age = 18 }) {}
Template literalsInterpolation and multiline`Hello ${name}`
map / filter / reduceMap / filter / reduce (all return a new value)arr.reduce((acc, x) => acc + x, 0)
find / findIndexFind the first element / indexarr.find(x => x.id === 1)
some / everyAny match / all match (short-circuits)arr.every(x => x > 0)
flat / flatMapFlatten an arrayarr.flat()
Promise.all / race / allSettledAll succeed / first settles / wait for all regardless of outcomePromise.allSettled([p1, p2])
import / exportESM named and default exportsexport const name = "value"

Common pitfalls

SymptomUsing var to declare a variable in a loop makes all items point to the last value.

Causevar is function-scoped rather than block-scoped, so the same binding is shared after the loop ends.

FixSwitch to let or const for block scoping.

SymptomUsing an arrow function as an object method makes this point to the outer scope instead of the object.

CauseArrow functions have no this of their own and capture the this from where they are defined.

FixUse the function shorthand for object methods, keeping this when you need to call the object itself.

SymptomUsing an async function inside forEach, but the loop does not wait for the async work to finish.

CauseforEach does not wait for the Promise returned by the callback.

FixSwitch to for...of with await, or map with Promise.all first and then await.

SymptomUsing Promise.all, one failure loses all the results.

Causeall rejects immediately on any reject and does not return the other completed results.

FixUse Promise.allSettled when you need to keep each result.

SymptomThe default parameter does not take effect and the value becomes undefined.

CauseExplicitly passing null does not trigger the default; only omitting or passing undefined does.

FixUse the x = 1 parameter, or handle null inside the function body with x ?? 1.

Symptompushing to a const-declared array throws an error.

CauseMisunderstanding of const semantics: it locks the reference, not the content.

FixA const array can be pushed to (its content is mutable), it just cannot be reassigned to another array; use Object.freeze to freeze the content.

Symptomreduce without an initial value produces NaN or throws.

CauseFor an empty array, reduce uses the first element as the initial value and the later operations fail.

FixAlways pass the second argument as the initial value, such as reduce((acc, x) => acc + x, 0).

SymptomAn ESM-imported module reports Unexpected token export in Node.

Causepackage.json does not declare "type": "module", so Node parses it as CommonJS.

FixSet "type": "module", or change the file extension to .mjs; for build output, let the bundler handle it.

Troubleshooting

  1. 1Confirm what this actually points to

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

    Run it once against an arrow function to see the difference; object methods must use a regular function.

  2. 2Correctly await async work inside a loop

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

    for...of awaits each in turn; forEach does not wait, which is the most common pitfall.

  3. 3Switch to allSettled when you need to keep each result

    Promise.allSettled([p1, p2])

    Returns the status and reason for each item, suited to batch tasks that must continue despite partial failures.

  4. 4Safely read a possibly missing key

    const { name = "anonymous", age } = person

    Destructuring defaults take effect only when the property is undefined and do not affect null.

  5. 5Always give reduce an initial value

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

    For an empty array, omitting the initial value errors; explicitly writing 0 is safest.

Command Examples

Transform an array with map in one go

[1, 2, 3].map((x) => x * 2)

map returns a new array of the same length without changing the original, suited to deriving view data.

Output

[2, 4, 6]

Destructure fields with a default value

const user = { name: "alice" } const { name, age = 18 } = user console.log(name, age)

Destructuring defaults take effect only when the property value is strictly undefined; null or an empty string is not replaced.

Output

alice 18

Await sequentially, then process

async function load() { const res = await fetch("/api/user") const data = await res.json() return data }

await suspends the following logic until the Promise settles, then continues; the outer layer must catch reject errors with try/catch.

Run promises in parallel with Promise.all

const [a, b] = await Promise.all([p1, p2])

Promise.all rejects as a whole on any reject; use Promise.allSettled when you want each result without dragging each other down.

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