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.4---5
6# Modern JavaScript & TypeScript
7
8## Before writing code
9
10**Fetch live docs**: Web-search `site:developer.mozilla.org javascript` for MDN JavaScript reference. Check `https://www.typescriptlang.org/docs/` for TypeScript documentation.
11
12## ES6+ Features
13
14### Arrow Functions
15
16Concise function syntax with lexical `this`:
17- `const add = (a, b) => a + b;`
18- Implicit return for single expressions
19- No own `this`, `arguments`, `super`, or `new.target`
20
21### Template Literals
22
23String interpolation and multi-line strings:
24- `` `Hello, ${name}!` ``
25- Tagged templates for DSLs
26
27### Destructuring
28
29Extract values from objects/arrays:
30- `const { name, price } = product;`
31- `const [first, ...rest] = items;`
32- Default values: `const { name = 'Unknown' } = product;`
33- Nested: `const { address: { city } } = customer;`
34
35### Spread / Rest
36
37- Spread: `[...arr1, ...arr2]`, `{ ...obj1, ...obj2 }`
38- Rest: `function(...args) {}`, `const { a, ...rest } = obj;`
39
40### Modules (ES Modules)
41
42- `import { func } from './module.js';`
43- `export const value = 42;` / `export default class {}`
44- Dynamic: `const mod = await import('./lazy.js');`
45
46### Optional Chaining & Nullish Coalescing
47
48- `obj?.property?.nested` — short-circuits to `undefined` if any part is nullish
49- `value ?? defaultValue` — returns right side only if left is `null`/`undefined` (not falsy)
50
51## Async Patterns
52
53### Promises
54
55- `new Promise((resolve, reject) => { ... })`
56- `.then()`, `.catch()`, `.finally()`
57- `Promise.all()`, `Promise.allSettled()`, `Promise.race()`, `Promise.any()`
58
59### Async/Await
60
61- `async function fetchData() { const data = await fetch(url); }`
62- Error handling with try/catch
63- Parallel: `const [a, b] = await Promise.all([fetchA(), fetchB()]);`
64
65### Fetch API
66
67```javascript
68const response = await fetch(url, {
69 method: 'POST',
70 headers: { 'Content-Type': 'application/json' },
71 body: JSON.stringify(data),
72});
73const result = await response.json();
74```
75
76## TypeScript
77
78### Type Annotations
79
80- `let name: string = 'Product';`
81- `function getPrice(id: number): Promise<number> { ... }`
82- `const product: Product = { ... };`
83
84### Interfaces
85
86```typescript
87interface Product {
88 id: number;
89 name: string;
90 price: number;
91 variants?: Variant[];
92}
93```
94
95### Type Utilities
96
97- `Partial<T>` — all properties optional
98- `Required<T>` — all properties required
99- `Pick<T, K>` — subset of properties
100- `Omit<T, K>` — exclude properties
101- `Record<K, V>` — key-value mapping
102- `ReturnType<T>` — extract return type of function
103
104### Generics
105
106```typescript
107function fetchResource<T>(url: string): Promise<T> {
108 return fetch(url).then(res => res.json());
109}
110const product = await fetchResource<Product>('/api/products/1');
111```
112
113### Enums
114
115```typescript
116enum OrderStatus {
117 Pending = 'pending',
118 Shipped = 'shipped',
119 Completed = 'completed',
120}
121```
122
123### Discriminated Unions
124
125```typescript
126type ApiResponse<T> =
127 | { status: 'success'; data: T }
128 | { status: 'error'; message: string };
129```
130
131## Modern Array Methods
132
133- `map`, `filter`, `reduce`, `find`, `findIndex`
134- `some`, `every` — boolean checks
135- `flat`, `flatMap` — array flattening
136- `Array.from()`, `Array.isArray()`
137- `Object.entries()`, `Object.fromEntries()`, `Object.keys()`, `Object.values()`
138- `structuredClone()` — deep clone
139
140## For BigCommerce Specifically
141
142### Stencil Theme JS
143
144- ES6 modules bundled with webpack
145- jQuery available (Cornerstone ships it)
146- Use `PageManager` lifecycle for page-specific code
147- Access injected server data via `this.context`
148
149### Catalyst / Next.js
150
151- TypeScript by default
152- React components with hooks
153- Server Components + Client Components
154- Type-safe GraphQL queries
155
156### App Development
157
158- Node.js backend with Express/Fastify
159- TypeScript for API type safety
160- JWT handling with `jsonwebtoken` library
161
162## Best Practices
163
164- Use `const` by default, `let` when reassignment is needed, never `var`
165- Use async/await over raw Promises for readability
166- Use TypeScript for all non-trivial projects
167- Use optional chaining to simplify null checks
168- Use destructuring for cleaner function signatures
169- Handle errors at appropriate levels (don't swallow errors)
170- Use `===` instead of `==` for comparisons
171- Use ESLint + Prettier for consistent code style
172
173Fetch MDN and TypeScript docs for exact syntax, browser compatibility, and new features before implementing.