ES6+ Core Features Cheat Sheet: Destructuring, Arrow Functions, Modules & Array Methods

A practical cheat sheet grouping the 20+ most-used ES6+ features by daily coding scenarios — scope declarations, template strings, destructuring, arrow functions, spread operator, optional chaining, nullish coalescing, Map/Set, modern array methods, and dynamic imports — with code examples, common pitfalls, and decision guidelines.

Code Farmer Manor Chronicle
Code Farmer Manor Chronicle
Code Farmer Manor Chronicle
ES6+ Core Features Cheat Sheet: Destructuring, Arrow Functions, Modules & Array Methods

ES6 (2015) and subsequent yearly releases introduced many features, but only about twenty are used daily. This cheat sheet filters by "what you write every day" and organizes by scenario so you don't pause to wonder if there's a more modern syntax.

01 Scope & Declarations

// var: function scope + hoisting (source of bugs)
// let / const: block scope + temporal dead zone
for (var i = 0; i < 3; i++) { }
console.log(i)          // 3 — var leaks out of loop

for (let j = 0; j < 3; j++) { }
console.log(j)          // ❌ ReferenceError — block scope doesn't leak

Rule: Default to const; use let only when reassignment is needed; ban var entirely.

02 Template Strings & Destructuring

① Template Strings

const msg = `${name} 的得分:${score.toFixed(1)}(${score >= 60 ? '及格' : '挂科'})`
// For String.format-style placeholders, wrap your own (JS has none natively)
const format = (tpl, ...args) =>
tpl.replace(/\{(\d+)\}/g, (_, i) => String(args[Number(i)]))
format('{0} 提交了 {1} 个文件', '张三', 3)

② Object/Array Destructuring (highest daily density)

// Array destructuring + default + skip
const [first, , third = '默认'] = [1, 2]
// Object destructuring + rename + default
const { name: userName, age = 18 } = user
// Nested destructuring: peel API response in one line
const { data: { records, total } } = await api.page(params)
// Function parameter destructuring + default: replaces options.xxx chains
function render({ rows = [], loading = false, onScroll } = {}) { ... }
// Swap variables
[a, b] = [b, a]

Pitfall: Destructuring defaults only trigger on undefined; null passes through. { timeout = 3000 } destructuring { timeout: null } yields null, not 3000. Sanitize before destructuring or use ?? as a guard.

03 Arrow Functions & this

// Arrow functions have no own this; they inherit from enclosing scope
const timer = setInterval(() => {
console.log(this.count)    // points to outer component instance
}, 1000)
// Regular function's this points to caller (event callback → DOM element)
button.addEventListener('click', function () {
console.log(this)          // button element
})

this : Arrow = lexical (definition site); Regular = dynamic (caller)

arguments : Arrow = none; Regular = available

Constructor : Arrow = ❌; Regular = ✅

Prototype method : Arrow = unsuitable; Regular = ✅

Rule: Use arrow functions for callbacks; use regular functions for object methods, prototype methods, and when arguments is needed.

04 Spread Operator & Shallow Copy

// Arrays: merge, clone, spread as arguments
const merged = [...arr1, ...arr2]
const copy = [...arr1]
// Objects: merge (later overrides earlier), conditional add
const merged = { ...defaults, ...overrides }
const payload = {
...basePayload,
...(withToken ? { Authorization: token } : {})
}
// Array deduplication
const unique = [...new Set(arr)]

Pitfall: Spread is shallow — nested objects still share references. For deep structures:

const deep = structuredClone(user)          // Recommended, supports Map/Set/circular refs
const deep2 = JSON.parse(JSON.stringify(user)) // Fallback, loses types

05 Optional Chaining & Nullish Coalescing (ES2020, eliminates 90% null checks)

// Optional chaining ?.: short-circuits to undefined if left side is null/undefined
const city = user?.address?.city              // three-level null check in one line
list?.[0]?.id                                 // dynamic index also uses ?.
fn?.()                                        // safe call when method may not exist

// Nullish coalescing ??: falls back only on null/undefined (key difference from ||)
const pageSize = query.size ?? 20             // size = 0 preserves 0
const bad = query.size || 20                  // ❌ size = 0 incorrectly becomes 20

null / undefined : ?? falls back ✅; || falls back ✅

0 / '' / false : ?? keeps original ✅ ; || falls back (mis-fires) ❌

Rule: Use ?? for numeric, string, and boolean flag fields; reserve || only for explicit "empty string/zero means invalid" semantics.

06 Map / Set

// Set: deduplication, membership test (faster & clearer than indexOf)
const tags = new Set(['a', 'b', 'a'])   // {'a','b'}
tags.has('a')                           // O(1)

// Map: keys can be any type, preserves insertion order, readable size
const userRoles = new Map()
userRoles.set(user1, ['admin', 'editor'])
for (const [user, roles] of userRoles) { ... }

Pitfall: Plain object keys are only strings/symbols — obj[user1] coerces the object to "[object Object]", causing different objects to overwrite each other. Use Map when keys are objects.

07 Array Methods by Scenario

① Query: find / findIndex / some / every

const target = rows.find(r => r.id === 2)        // find element
const idx = rows.findIndex(r => r.id === 2)     // find index
const hasDraft = rows.some(r => r.status === 0) // any match → true
const allDone = rows.every(r => r.status === 1) // all match → true

② Transform: map / filter / flat / flatMap

const names = rows.map(r => r.name)              // one-to-one transform
const nested = [[1, 2], [3, [4]]]
nested.flat()          // [1, 2, 3, [4]]
nested.flat(Infinity)  // [1, 2, 3, 4]
const pairs = words.flatMap(w => [w, w.toUpperCase()])

· Pitfall: map without a return value produces an array of undefined — use forEach for pure side effects.

③ Reduce: reduce (array → arbitrary structure)

// Grouping: one-liner turns flat list into object keyed by field
const groupBy = (list, keyFn) =>
list.reduce((acc, item) => {
const key = keyFn(item)
;(acc[key] ??= []).push(item)
return acc
}, {})

const total = items.reduce((sum, it) => sum + it.price * it.count, 0)

Pitfall: Always provide an initial value (especially {} for object accumulation); omitting it throws on empty arrays.

④ Immutable Sort & Mutations (ES2022/2023 additions)

// sort mutates in place — Vue reactivity may lose change tracking
const sorted = rows.toSorted((a, b) => a.id - b.id)      // ES2023
const withoutFirst = rows.toSpliced(0, 1)                // ES2023
rows.at(-1)          // last element, replaces rows[rows.length - 1]

08 Modules & Dynamic Import

// Named + default export mixed
import request, { get, post } from '@/utils/request'
// Dynamic import: route lazy-loading, bundle-size optimization core technique
const Chart = () => import('echarts')                    // route component
const { open } = await import('./heavy-module.js')     // conditional load
const mod = await import('./plugin.js').catch(() => null) // error fallback

09 Quick-Reference Summary

Multi-level null check : a?.b?.c

Null/undefined fallback : ?? (0 and empty string preserved)

Merge objects/arrays : { ...a, ...b } / [...a, ...b] Deep clone : structuredClone Find element/index : find / findIndex Existence / all match : some / every Group & aggregate : reduce Tail access : at(-1) Immutable sort : toSorted Array deduplicate : [...new Set(arr)] Object as key : Map

Lazy-load module : import() Takeaway: ES6+ isn't about memorizing every yearly syntax addition; the real daily value lives in these twenty-odd points — null-check chains, destructuring instead of chained property access, immutable methods that preserve reactivity. Internalize them into muscle memory and both coding ergonomics and engineering quality will step up a notch.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptArrow FunctionsOptional ChainingES6Array MethodsDestructuringES2020Nullish Coalescing
Code Farmer Manor Chronicle
Written by

Code Farmer Manor Chronicle

A heart like drifting clouds, ever at ease; a mind like flowing water, free to roam.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.