React Foundations / Start Here

The JavaScript React code relies on

Lesson 4 of 35. Open to read. No account needed.

React code is ordinary modern JavaScript, and a handful of language features appear on almost every line. This lesson is a check, not a JavaScript course. For each feature you read a short program, predict what it prints, then run it and compare. Where your prediction was wrong, the explanation below the output shows what to look at.

If you predict most of them correctly, you are ready. If most surprise you, spend some time with a JavaScript course first; the rest of this course will make much more sense afterwards.

Setting Up

You need Node.js from Set up Node.js and run your first React app. In a terminal, create a folder for the snippets inside the practice folder:

cd ~/react-foundations-practice
mkdir js-bridge
cd js-bridge

Save each program below in that folder with the file name shown on its first line, then run it with node and the file name, for example node 1-arrow-functions.mjs. The first line of each code block is a comment naming the file, as in all code blocks in this course; including it in your file does no harm.

The files end in .mjs so that Node.js treats them as modules, which allows import and export. A React project gets the same effect from "type": "module" in its package.json.

The outputs shown were captured by running these exact files with Node.js 24.

1. Arrow Functions

// 1-arrow-functions.mjs
const double = (n) => n * 2
const describe = (book) => `${book.title} by ${book.author}`

console.log(double(21))
console.log(describe({ title: 'Small Engines of Spring', author: 'Tomas Lind' }))

Predict both lines, then run it.

42
Small Engines of Spring by Tomas Lind

An arrow function with no braces after => returns its expression automatically. The backtick string is a template literal: ${...} inserts a value. React code uses arrow functions constantly, for event handlers such as () => setCount(count + 1) and for map callbacks that turn data into page content.

2. Destructuring

// 2-destructuring.mjs
const book = { id: 'b2', title: 'Small Engines of Spring', author: 'Tomas Lind' }

const { title, note = 'No note' } = book
console.log(title, '|', note)

const pair = ['read', 'unread']
const [first, second] = pair
console.log(first, '|', second)

function showCard({ title, author }) {
  return `${title} (${author})`
}
console.log(showCard(book))

Predict all three lines. What does note become, given that book has no note property?

Small Engines of Spring | No note
read | unread
Small Engines of Spring (Tomas Lind)

Object destructuring copies properties into variables of the same name; = 'No note' is a default used when the property is missing (undefined). Array destructuring takes items by position, so the names are yours to choose. A function can destructure its parameter directly, as showCard does.

All three appear in React. Components receive their inputs as one object and usually destructure it in the parameter list, exactly like showCard. State comes from a function that returns a two-item array, unpacked as const [count, setCount] = ....

3. Spread Copies, and Why They Are Shallow

// 3-spread-copies.mjs
const original = { title: 'A Map of Quiet Rivers', done: false, tags: ['travel'] }

const copy = { ...original, done: true }
console.log(original.done, copy.done)

copy.tags.push('slow read')
console.log(original.tags)
console.log(original.tags === copy.tags)

const numbers = [1, 2, 3]
const more = [...numbers, 4]
console.log(numbers.length, more.length)

This is the one most people get wrong. Predict the second and third lines carefully.

false true
[ 'travel', 'slow read' ]
true
3 4

{ ...original, done: true } creates a new object with the same properties, then overrides done, so original.done is still false. But the copy is shallow: its tags property points to the same array as the original's. Pushing into copy.tags therefore changes the array both objects share, which is why original.tags shows the new item and === reports true (same array). [...numbers, 4] likewise builds a new array and leaves numbers alone.

React relies on new objects and arrays to notice that data changed, so you will use spread every time you update data. The shallow-copy trap is the cause of some of the most confusing bugs; a later lesson, Update objects and arrays in state, shows how to copy each level that changes.

4. Modules: Named and Default Exports

This one needs two files. Save the data module first:

// books.mjs
export const sampleBooks = [
  { id: 'b1', title: 'The Lighthouse Ledger', read: true },
  { id: 'b2', title: 'Small Engines of Spring', read: false },
  { id: 'b3', title: 'A Map of Quiet Rivers', read: false },
]

export default function countBooks(books) {
  return books.length
}
// 4-modules.mjs
import howMany, { sampleBooks } from './books.mjs'

console.log(howMany(sampleBooks))

books.mjs exports a function called countBooks, but 4-modules.mjs never mentions that name. Predict whether this works, and what it prints.

3

A file has at most one default export, and the importing file chooses its local name: howMany here. Named exports are imported in braces under their exact names, so { sampleBooks } must match. ./ means "in the same folder as this file".

React projects use both. Each component usually lives in its own file as a default export (import App from './App.jsx'), while helpers and data are named exports.

5. map, filter and find

// 5-array-methods.mjs
import { sampleBooks } from './books.mjs'

const titles = sampleBooks.map((book) => book.title)
console.log(titles)

const unread = sampleBooks.filter((book) => !book.read)
console.log(unread.length)

console.log(sampleBooks.find((book) => book.id === 'b3').title)
console.log(sampleBooks.find((book) => book.id === 'b9'))

Predict each line, especially the last.

[
  'The Lighthouse Ledger',
  'Small Engines of Spring',
  'A Map of Quiet Rivers'
]
2
A Map of Quiet Rivers
undefined

map returns a new array with one result per item; filter returns a new array of the items for which the function returns true; find returns the first matching item, or undefined if none matches. None of them changes the original array. (Node.js prints a longer array on several lines; that is only formatting.)

In React, map turns an array of data into a list on the page, and filter chooses which items to show. If find returns undefined and the code goes on to read .title from it, the program stops with an error, a common cause of a blank page.

6. async, await and the Response Object

// 6-async-await.mjs
// A stand-in for a server's reply: fetch resolves to an object like this.
async function pretendFetch() {
  return new Response('Not found', { status: 404 })
}

async function load() {
  console.log('2: request sent')
  const response = await pretendFetch()
  console.log('4: status', response.status, 'ok?', response.ok)
}

console.log('1: before load')
load()
console.log('3: after calling load')

There is no server here: pretendFetch returns the same kind of Response object the real fetch gives you, built into Node.js and browsers alike. Predict the order of the four lines, and whether ok? is true.

1: before load
2: request sent
3: after calling load
4: status 404 ok? false

An async function runs until its first await, then pauses and returns control to whoever called it. That is why line 3 prints before line 4: the code after load() does not wait. When the awaited promise settles, load resumes.

The second point matters a great deal later: a reply with status 404 is still a successful response. fetch does not treat it as an error. You must check response.ok (true for statuses 200 to 299) yourself. The data-loading lessons build on exactly this.

Your Turn: Copy Without Changing

Write a function addTag(book, tag) that returns a new book with tag added to its tags array, without changing the book passed in. Prove it by logging the original's tags and the new book's tags. Save it as add-tag.mjs.

Think about snippet 3 before you start.

Hints

  1. Spreading the book gives a new object, but its tags would still be the original array.
  2. The tags property needs its own new array too.

Solution

// add-tag.mjs
function addTag(book, tag) {
  return { ...book, tags: [...book.tags, tag] }
}

const book = { title: 'Notes from the Night Train', tags: ['mystery'] }
const tagged = addTag(book, 'favourite')
console.log(book.tags)
console.log(tagged.tags)
[ 'mystery' ]
[ 'mystery', 'favourite' ]

The outer spread copies the book; tags: [...book.tags, tag] replaces its tags with a new array containing the old items plus the new one. Calling book.tags.push(tag) instead would change the original, which is exactly the mistake snippet 3 demonstrated. React's state updates follow this same pattern.

How Did You Do?

Count the snippets you predicted correctly before running them, not counting the Your Turn task.

  • 5 or 6: you are ready. Carry on to the next module.
  • 3 or 4: you are probably ready. Re-read the explanations for the ones you missed. They come back in the lessons linked above, where they are explained again in context.
  • 0 to 2: take time to learn modern JavaScript first, then return. The course assumes these features and does not stop to teach the language.

Nothing records your score; this is for you.

Reset and Clean Up

Nothing else in the course uses js-bridge. When you are finished, delete the js-bridge folder inside react-foundations-practice using your file manager. Check that you are deleting js-bridge and not the practice folder itself.

References

30 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy