Appendix A

JavaScript Refresher

The modern JavaScript (ES6+) features that React code uses constantly, with a quick example and a check question for each.

Covered here
  • let / const, arrow functions, template literals
  • Destructuring, spread & rest, shorthand and computed properties
  • Array methods: map, filter, reduce, find, some/every, and which ones mutate
  • Ternary, &&, ||, ??, optional chaining ?., truthy/falsy
  • Modules, Promises with async/await, closures, and reference equality
How to use this appendix Read it before Chapter 2 if your JavaScript is rusty, or come back whenever React code looks confusing. Usually it's one of these features. Try each Quick check before opening the answer. You can run any example in the browser console (F12 โ†’ Console).

1. let and const

Use const for values you won't reassign (most of them), and let for values you will. Avoid the old var, which has confusing scoping rules.

In React: const [count, setCount] = useState(0). You never reassign count; you call the setter.

Quick check

Does const user = { age: 30 }; user.age = 31; throw an error?

Show answer

No. The variable still points to the same object, and only a property inside it changed. (In React state you still shouldn't do this. See Chapter 8.)

2. Arrow functions

A shorter way to write functions, and the most common style in React code.

In React: onClick={() => setOpen(true)} and items.map(item => <li>{item}</li>).

Quick check

What does const f = () => { value: 1 }; f() return?

Show answer

undefined. The braces are read as a function body (with a label called "value"), not an object. Write () => ({ value: 1 }).

3. Template literals

Strings in backticks can contain ${expression} and span several lines.

In React: className={`card ${isActive ? 'active' : ''}`} and building image URLs.

Quick check

What is `${2 + 3} apples`?

Show answer

"5 apples": the expression is evaluated first.

4. Destructuring

Objects: pull properties out by name

Arrays: pull items out by position

In function parameters

In React: every component's props, function Avatar({ person, size }), and every Hook, const [value, setValue] = useState().

Defaults only apply to undefined const { size = 10 } = { size: null } gives null, not 10. The same applies to 0 and '': the default is not used.

Quick check

After const [a, b = 5] = [1];, what are a and b?

Show answer

a = 1 and b = 5. There is no second item, so the default is used.

5. Spread ... and rest ...

The same three dots do two opposite jobs. Spread expands items out, and rest collects them in.

In React: updating state without mutation, setTodos([...todos, newTodo]) and setForm({ ...form, email }), and forwarding props with <Child {...props} />.

Spread is shallow { ...person } copies only the top level. Nested objects are still shared with the original.

Quick check

What is { ...{ a: 1, b: 2 }, ...{ b: 3 } }?

Show answer

{ a: 1, b: 3 }. The later b wins.

6. Shorthand and computed properties

In React: one change handler for many inputs: setForm({ ...form, [e.target.name]: e.target.value }).

Quick check

If const key = 'color', what is { [key + 'Name']: 'red' }?

Show answer

{ colorName: 'red' }. Any expression can go in the brackets.

7. Array methods you'll use every day

Mutating vs non-mutating

๐Ÿ”ด Changes the originalโœ… Returns something new
push, pop, shift, unshift, splice, sort, reverse, fill map, filter, slice, concat, toSorted, toReversed, toSpliced, with

In React: map renders lists, filter removes items from state, find gets the selected item, and reduce calculates totals. Never use the mutating ones on state.

Sorting numbers [10, 9, 1].toSorted() gives [1, 10, 9], because the default sort compares items as strings. Use toSorted((a, b) => a - b).

Quick check

What does [3, 8, 1].map(n => n > 2) return?

Show answer

[true, true, false]. map keeps the length and replaces each item with what the function returns. (To keep only some items, use filter.)

8. Conditional expressions: ? :, &&, ||, ??

In React: {isLoggedIn ? <Logout /> : <Login />}, {error && <p>{error}</p>}, and {user.nickname ?? user.name}.

The "0" bug {count && <Badge />} shows 0 when count is 0. Write {count > 0 && <Badge />}.

Quick check

A user's volume setting is 0. Which gives the right result: volume || 50 or volume ?? 50?

Show answer

volume ?? 50 gives 0, which is correct. || treats 0 as falsy and wrongly returns 50.

9. Optional chaining ?.

In React: rendering data that loads later, {data?.title}, and optional callback props.

Quick check

What is undefined?.length?

Show answer

undefined, with no error.

10. Truthy and falsy

In conditions, every value acts as either true or false. The falsy values are:

Everything else is truthy, including '0', 'false', [], {} and -1.

Quick check

Does if ([]) { ... } run its block?

Show answer

Yes, an empty array is truthy. To check for emptiness, use items.length > 0.

11. Modules: import and export

Quick check

The file exports export function Card(). Does import Card from './Card' work?

Show answer

No. That's a named export, so use import { Card } from './Card'.

12. Promises, async / await and fetch

A Promise is a value that arrives later. await pauses an async function until the value arrives, without freezing the page.

In React: fetching data inside Effects or event handlers (Chapter 13).

Quick check

What does const data = fetch(url) (without await) put in data?

Show answer

A Promise, not the data. You need await (or .then) twice: once for the response and once for res.json().

13. Closures

A function remembers the variables from the place where it was created, even after that place has finished running.

In React: every event handler is a closure over the props and state of its render. That's why setTimeout(() => alert(count), 3000) shows the old value (the "state as a snapshot" idea in Chapter 7).

Quick check

Each button in items.map(item => <button onClick={() => remove(item.id)}>) removes the right item. Why?

Show answer

Each arrow function is a closure that remembers its own item from that iteration of the map.

14. Reference equality

Primitives (numbers, strings, booleans) compare by value. Objects and arrays compare by reference, meaning "is it the very same object?"

In React: this is exactly why you must create new objects and arrays when updating state. React checks oldState === newState (strictly, Object.is) to decide whether anything changed.

Quick check

You do items.push(x); setItems(items);. Why might React not re-render?

Show answer

It's the same array reference, so React sees "no change". Use setItems([...items, x]).

Recap: the React connection

JS featureWhere you see it in React
DestructuringProps ({ name }) and Hooks [x, setX]
SpreadImmutable updates: { ...obj }, [...arr]
map / filterRendering lists and removing items
Arrow functionsEvent handlers and callbacks
? : / && / ??Conditional rendering
Template literalsDynamic class names and URLs
ModulesSplitting components into files
async/awaitFetching data
ClosuresHandlers seeing "their" render's state
Reference equalityWhy state must be replaced, not mutated

Exercises

1. Destructure a response ๐ŸŸข easy

From const res = { data: { user: { name: 'Asha', role: 'admin' } }, status: 200 }, get name, role and status into variables in one statement.

Show solution

2. Prices with tax ๐ŸŸข easy

Turn [100, 250, 40] into ['โ‚น118', 'โ‚น295', 'โ‚น47.2'] (18% tax) using map and a template literal.

Show solution

+(...).toFixed(2) rounds to 2 decimal places, then turns the result back into a number, which drops trailing zeros.

3. Adults only ๐ŸŸข easy

From an array of { name, age }, get just the names of people aged 18 or over.

Show solution

4. Cart total ๐ŸŸข easy

Calculate the total of [{ price: 50, qty: 2 }, { price: 30, qty: 1 }] with reduce.

Show solution

5. Update without mutating ๐ŸŸก medium

Given const user = { name: 'Asha', settings: { theme: 'light', lang: 'en' } }, create a NEW object with theme: 'dark'. The original must stay unchanged.

Show solution

6. Safe access with defaults ๐ŸŸก medium

Write getCity(user), which returns the user's city, or 'Unknown' if user, user.address or the city is missing. Use one line.

Show solution

7. Group by category ๐ŸŸก medium

Turn [{ name: 'Apple', cat: 'fruit' }, { name: 'Peas', cat: 'veg' }, { name: 'Kiwi', cat: 'fruit' }] into { fruit: ['Apple', 'Kiwi'], veg: ['Peas'] } with reduce.

Show solution

Modern browsers also have Object.groupBy(items, i => i.cat), which gives arrays of the whole objects.

8. Fetch and show ๐ŸŸก medium

Write an async function that fetches https://jsonplaceholder.typicode.com/todos?_limit=5 and returns just the titles of the completed todos.

Show solution

9. Spot the mutations ๐ŸŸก medium

Which lines change the original list?

Show answer

Lines 2 (sort) and 4 (splice). Line 3 reverses a copy.

10. Build a tiny "useState" ๐Ÿ”ด hard

Using closures, write createState(initial), which returns [get, set]. get() returns the current value, and set(v) updates it and logs "re-render with v". (This is a toy model of how React keeps state outside your function.)

Show solution
Ready to test yourself? The Final Assessment includes a large set of JavaScript questions alongside the React ones.