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.
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"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 {}Parameter matrix
| Parameter | Effect | Example |
|---|---|---|
const vs let | Cannot be reassigned / can be reassigned, both block-scoped | const name = "value" |
Arrow function | Omits return, does not bind its own this | const fn = (x) => x * 2 |
Default parameters | Takes effect only when not passed or explicitly passed undefined | const fn = (x, y = 1) => {} |
Rest parameters ...rest | Collects extra arguments into a real array | const fn = (...args) => {} |
function* / yield | Generator, produces values lazily on demand | function* generator() { yield 1; } |
Array destructuring + rest | Take the first item and the remaining items | const [first, ...rest] = arr |
Object destructuring rename | When the property name and variable name differ | const { name: userName } = person |
Function parameter destructuring | Parameters are expanded directly and can carry defaults | function fn({ name, age = 18 }) {} |
Template literals | Interpolation and multiline | `Hello ${name}` |
map / filter / reduce | Map / filter / reduce (all return a new value) | arr.reduce((acc, x) => acc + x, 0) |
find / findIndex | Find the first element / index | arr.find(x => x.id === 1) |
some / every | Any match / all match (short-circuits) | arr.every(x => x > 0) |
flat / flatMap | Flatten an array | arr.flat() |
Promise.all / race / allSettled | All succeed / first settles / wait for all regardless of outcome | Promise.allSettled([p1, p2]) |
import / export | ESM named and default exports | export 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
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.
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.
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.
4Safely read a possibly missing key
const { name = "anonymous", age } = personDestructuring defaults take effect only when the property is undefined and do not affect null.
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