Modern JavaScript & TypeScript
Before writing code
Fetch live docs: Web-search site:developer.mozilla.org javascript for MDN JavaScript reference. Check https://www.typescriptlang.org/docs/ for TypeScript documentation.
ES6+ Features
Arrow Functions
Concise function syntax with lexical this:
const add = (a, b) => a + b;
- Implicit return for single expressions
- No own
this, arguments, super, or new.target
Template Literals
String interpolation and multi-line strings:
`Hello, ${name}!`
- Tagged templates for DSLs
Destructuring
Extract values from objects/arrays:
const { name, price } = product;
const [first, ...rest] = items;
- Default values:
const { name = 'Unknown' } = product;
- Nested:
const { address: { city } } = customer;
Spread / Rest
- Spread:
[...arr1, ...arr2], { ...obj1, ...obj2 }
- Rest:
function(...args) {}, const { a, ...rest } = obj;
Modules (ES Modules)
import { func } from './module.js';
export const value = 42; / export default class {}
- Dynamic:
const mod = await import('./lazy.js');
Optional Chaining & Nullish Coalescing
obj?.property?.nested — short-circuits to undefined if any part is nullish
value ?? defaultValue — returns right side only if left is null/undefined (not falsy)
Async Patterns
Promises
new Promise((resolve, reject) => { ... })
.then(), .catch(), .finally()
Promise.all(), Promise.allSettled(), Promise.race(), Promise.any()
Async/Await
async function fetchData() { const data = await fetch(url); }
- Error handling with try/catch
- Parallel:
const [a, b] = await Promise.all([fetchA(), fetchB()]);
Fetch API
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
const result = await response.json();
TypeScript
Type Annotations
let name: string = 'Product';
function getPrice(id: number): Promise<number> { ... }
const product: Product = { ... };
Interfaces
interface Product {
id: number;
name: string;
price: number;
variants?: Variant[];
}
Type Utilities
Partial<T> — all properties optional
Required<T> — all properties required
Pick<T, K> — subset of properties
Omit<T, K> — exclude properties
Record<K, V> — key-value mapping
ReturnType<T> — extract return type of function
Generics
function fetchResource<T>(url: string): Promise<T> {
return fetch(url).then(res => res.json());
}
const product = await fetchResource<Product>('/api/products/1');
Enums
enum OrderStatus {
Pending = 'pending',
Shipped = 'shipped',
Completed = 'completed',
}
Discriminated Unions
type ApiResponse<T> =
| { status: 'success'; data: T }
| { status: 'error'; message: string };
Modern Array Methods
map, filter, reduce, find, findIndex
some, every — boolean checks
flat, flatMap — array flattening
Array.from(), Array.isArray()
Object.entries(), Object.fromEntries(), Object.keys(), Object.values()
structuredClone() — deep clone
For BigCommerce Specifically
Stencil Theme JS
- ES6 modules bundled with webpack
- jQuery available (Cornerstone ships it)
- Use
PageManager lifecycle for page-specific code
- Access injected server data via
this.context
Catalyst / Next.js
- TypeScript by default
- React components with hooks
- Server Components + Client Components
- Type-safe GraphQL queries
App Development
- Node.js backend with Express/Fastify
- TypeScript for API type safety
- JWT handling with
jsonwebtoken library
Best Practices
- Use
const by default, let when reassignment is needed, never var
- Use async/await over raw Promises for readability
- Use TypeScript for all non-trivial projects
- Use optional chaining to simplify null checks
- Use destructuring for cleaner function signatures
- Handle errors at appropriate levels (don't swallow errors)
- Use
=== instead of == for comparisons
- Use ESLint + Prettier for consistent code style
Fetch MDN and TypeScript docs for exact syntax, browser compatibility, and new features before implementing.
1---2name: js-modern3description: Write modern JavaScript and TypeScript — ES6+ features, async/await, modules, destructuring, optional chaining, TypeScript types, and modern tooling. Use when writing JavaScript/TypeScript for BigCommerce themes, apps, or headless storefronts.4allowed-tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch5metadata:6 source: https://skillmd.com/skills/orcaqubits/js-modern7---89# Modern JavaScript & TypeScript1011## Before writing code1213**Fetch live docs**: Web-search `site:developer.mozilla.org javascript` for MDN JavaScript reference. Check `https://www.typescriptlang.org/docs/` for TypeScript documentation.1415## ES6+ Features1617### Arrow Functions1819Concise function syntax with lexical `this`:20- `const add = (a, b) => a + b;`21- Implicit return for single expressions22- No own `this`, `arguments`, `super`, or `new.target`2324### Template Literals2526String interpolation and multi-line strings:27- `` `Hello, ${name}!` ``28- Tagged templates for DSLs2930### Destructuring3132Extract values from objects/arrays:33- `const { name, price } = product;`34- `const [first, ...rest] = items;`35- Default values: `const { name = 'Unknown' } = product;`36- Nested: `const { address: { city } } = customer;`3738### Spread / Rest3940- Spread: `[...arr1, ...arr2]`, `{ ...obj1, ...obj2 }`41- Rest: `function(...args) {}`, `const { a, ...rest } = obj;`4243### Modules (ES Modules)4445- `import { func } from './module.js';`46- `export const value = 42;` / `export default class {}`47- Dynamic: `const mod = await import('./lazy.js');`4849### Optional Chaining & Nullish Coalescing5051- `obj?.property?.nested` — short-circuits to `undefined` if any part is nullish52- `value ?? defaultValue` — returns right side only if left is `null`/`undefined` (not falsy)5354## Async Patterns5556### Promises5758- `new Promise((resolve, reject) => { ... })`59- `.then()`, `.catch()`, `.finally()`60- `Promise.all()`, `Promise.allSettled()`, `Promise.race()`, `Promise.any()`6162### Async/Await6364- `async function fetchData() { const data = await fetch(url); }`65- Error handling with try/catch66- Parallel: `const [a, b] = await Promise.all([fetchA(), fetchB()]);`6768### Fetch API6970```javascript71const response = await fetch(url, {72 method: 'POST',73 headers: { 'Content-Type': 'application/json' },74 body: JSON.stringify(data),75});76const result = await response.json();77```7879## TypeScript8081### Type Annotations8283- `let name: string = 'Product';`84- `function getPrice(id: number): Promise<number> { ... }`85- `const product: Product = { ... };`8687### Interfaces8889```typescript90interface Product {91 id: number;92 name: string;93 price: number;94 variants?: Variant[];95}96```9798### Type Utilities99100- `Partial<T>` — all properties optional101- `Required<T>` — all properties required102- `Pick<T, K>` — subset of properties103- `Omit<T, K>` — exclude properties104- `Record<K, V>` — key-value mapping105- `ReturnType<T>` — extract return type of function106107### Generics108109```typescript110function fetchResource<T>(url: string): Promise<T> {111 return fetch(url).then(res => res.json());112}113const product = await fetchResource<Product>('/api/products/1');114```115116### Enums117118```typescript119enum OrderStatus {120 Pending = 'pending',121 Shipped = 'shipped',122 Completed = 'completed',123}124```125126### Discriminated Unions127128```typescript129type ApiResponse<T> =130 | { status: 'success'; data: T }131 | { status: 'error'; message: string };132```133134## Modern Array Methods135136- `map`, `filter`, `reduce`, `find`, `findIndex`137- `some`, `every` — boolean checks138- `flat`, `flatMap` — array flattening139- `Array.from()`, `Array.isArray()`140- `Object.entries()`, `Object.fromEntries()`, `Object.keys()`, `Object.values()`141- `structuredClone()` — deep clone142143## For BigCommerce Specifically144145### Stencil Theme JS146147- ES6 modules bundled with webpack148- jQuery available (Cornerstone ships it)149- Use `PageManager` lifecycle for page-specific code150- Access injected server data via `this.context`151152### Catalyst / Next.js153154- TypeScript by default155- React components with hooks156- Server Components + Client Components157- Type-safe GraphQL queries158159### App Development160161- Node.js backend with Express/Fastify162- TypeScript for API type safety163- JWT handling with `jsonwebtoken` library164165## Best Practices166167- Use `const` by default, `let` when reassignment is needed, never `var`168- Use async/await over raw Promises for readability169- Use TypeScript for all non-trivial projects170- Use optional chaining to simplify null checks171- Use destructuring for cleaner function signatures172- Handle errors at appropriate levels (don't swallow errors)173- Use `===` instead of `==` for comparisons174- Use ESLint + Prettier for consistent code style175176Fetch MDN and TypeScript docs for exact syntax, browser compatibility, and new features before implementing.