Programming58 entries

JavaScript ES6+

Modern JavaScript syntax: destructuring, arrow functions, promises, modules, and built-in methods

1Variables & Declarations

const x = 1
Block-scoped, read-only constant
let y = 2
Block-scoped variable
const [a, b] = [1, 2]
Array destructuring
const { name, age } = obj
Object destructuring
const { name: n } = obj
Destructuring with rename
const { x = 10 } = obj
Destructuring with default

2Arrow Functions

const fn = (a, b) => a + b
Arrow function (implicit return)
const fn = (a) => { return a * 2 }
Arrow function with body
const fn = a => a * 2
Single param (no parens needed)
arr.map(x => x * 2)
Arrow function as callback
arr.filter(x => x > 5)
Filter with arrow function

3Template Literals & Strings

`Hello ${name}`
Template literal with interpolation
`multi\nline`
Multi-line string
str.includes("sub")
Check if string contains substring
str.startsWith("pre")
Check if starts with
str.endsWith("suf")
Check if ends with
str.repeat(3)
Repeat string n times
str.padStart(5, "0")
Pad string from start
str.trimStart() / str.trimEnd()
Trim whitespace from start/end

4Spread & Rest

[...arr1, ...arr2]
Spread arrays (merge)
{ ...obj1, ...obj2 }
Spread objects (merge)
const [first, ...rest] = arr
Rest in destructuring
function fn(...args) {}
Rest parameters
fn(...args)
Spread as function arguments

5Array Methods

arr.map(fn)
Transform each element
arr.filter(fn)
Keep elements matching condition
arr.reduce(fn, init)
Reduce to single value
arr.find(fn)
Find first matching element
arr.findIndex(fn)
Find index of first match
arr.some(fn)
Test if any element matches
arr.every(fn)
Test if all elements match
arr.includes(val)
Check if value exists
arr.flat(depth)
Flatten nested arrays
arr.flatMap(fn)
Map then flatten one level
Array.from(iterable)
Create array from iterable
structuredClone(obj)
Deep clone object/array

6Objects & Classes

{ name, age }
Shorthand property names
{ [key]: value }
Computed property names
{ method() {} }
Shorthand method
Object.keys(obj)
Get array of keys
Object.values(obj)
Get array of values
Object.entries(obj)
Get array of [key, value] pairs
Object.assign({}, obj)
Shallow copy / merge objects
obj?.nested?.prop
Optional chaining
val ?? defaultVal
Nullish coalescing

7Promises & Async

new Promise((resolve, reject) => {})
Create a promise
promise.then(fn).catch(fn)
Handle promise result/error
async function fn() {}
Async function declaration
const result = await promise
Await promise resolution
Promise.all([p1, p2])
Wait for all promises
Promise.allSettled([p1, p2])
Wait for all (resolved or rejected)
Promise.race([p1, p2])
First promise to settle wins

8Modules

export const x = 1
Named export
export default fn
Default export
import { x } from "./mod"
Named import
import fn from "./mod"
Default import
import * as mod from "./mod"
Import all as namespace
const mod = await import("./mod")
Dynamic import