JS 25

Chapter 25 — JavaScript Patterns for React ⭐⭐⭐⭐⭐

🎯 Goal (1 line)

Learn the JavaScript patterns that appear in almost every React application.

Important: This is not React yet. Think of it as learning the "grammar" before speaking the language. Once you know these patterns, React becomes much easier.


The 20% You'll Use 80% of the Time

You'll see these patterns every day in React:

✅ Updating arrays without changing the original

✅ Updating objects without changing the original

✅ Using map() to display lists

✅ Using filter() to remove items

✅ Using find() to locate an item

✅ Using some() and every()

✅ Chaining array methods

✅ Writing pure functions

✅ Avoiding mutations


MCQ 1 (Easy)

Which array should you use for a list of users?

A.

const users = {
  name: "Alice"
};

B.

const users = [
  { name: "Alice" },
  { name: "Bob" }
];

C.

const users = "Alice,Bob";

D.

const users = 2;

✅ Answer

B

React usually stores collections as arrays of objects.


MCQ 2

Which method creates a new array?

A.

map()

B.

filter()

C.

slice()

D.

All of the above


✅ Answer

D

These methods return new arrays without changing the original.


MCQ 3

Output?

const nums = [1, 2, 3];

const doubled = nums.map(n => n * 2);

console.log(doubled);

A.

[1,2,3]

B.

[2,4,6]

C.

6

D.

Error


✅ Answer

B

map() transforms every element.


MCQ 4

Output?

const nums = [1, 2, 3];

console.log(nums);

After this code:

nums.map(n => n * 2);

A.

[2,4,6]

B.

[1,2,3]

C.

Error

D.

undefined


✅ Answer

B

map() does not change the original array.


MCQ 5

Which removes inactive users?

const users = [
  { active: true },
  { active: false },
  { active: true }
];

A.

users.filter(user => user.active)

B.

users.find(user => user.active)

C.

users.map(user => user.active)

D.

users.some(user => user.active)

✅ Answer

A

filter() keeps only matching items.


MCQ 6

Output?

const nums = [5, 10, 15];

console.log(
  nums.find(n => n > 8)
);

A.

10

B.

15

C.

[10,15]

D.

Error


✅ Answer

A

find() returns the first matching item.


MCQ 7

Which method checks whether at least one item matches?

A.

every()

B.

some()

C.

find()

D.

map()


✅ Answer

B

some() returns true if at least one item matches.


MCQ 8

Output?

const scores = [80, 90, 70];

console.log(
  scores.every(score => score >= 60)
);

A.

true

B.

false

C.

70

D.

undefined


✅ Answer

A

Every score is at least 60.


MCQ 9

Output?

const scores = [80, 90, 40];

console.log(
  scores.every(score => score >= 60)
);

A.

true

B.

false

C.

40

D.

undefined


✅ Answer

B

One score is below 60.


MCQ 10

Which is the React-friendly way to add a user?

A.

users.push(newUser);

B.

const updatedUsers = [...users, newUser];

C.

users[users.length] = newUser;

D.

users = users.push(newUser);

✅ Answer

B

React prefers creating new arrays, not modifying existing ones.


MCQ 11

Which updates a user's age correctly?

const user = {
  name: "Alice",
  age: 25
};

A.

user.age = 26;

B.

const updatedUser = {
  ...user,
  age: 26
};

C.

delete user.age;

D.

user = {};

✅ Answer

B

Create a new object instead of changing the original.


MCQ 12

Output?

const user = {
  name: "Sam",
  age: 20
};

const updated = {
  ...user,
  age: 21
};

console.log(updated.age);

A.

20

B.

21

C.

undefined

D.

Error


✅ Answer

B

The spread operator copies the object, then age is overwritten.


MCQ 13

Which removes a todo?

const todos = [
  { id: 1 },
  { id: 2 },
  { id: 3 }
];

Remove id === 2.

A.

todos.splice(1,1);

B.

todos.filter(todo => todo.id !== 2);

C.

todos.pop();

D.

todos.shift();

✅ Answer

B

filter() returns a new array without the removed item.


MCQ 14

Output?

const nums = [1,2,3];

const result =
nums
  .map(n => n * 2)
  .filter(n => n > 2);

console.log(result);

A.

[2]

B.

[4,6]

C.

[2,4]

D.

Error


✅ Answer

B

Step-by-step:

map()

[2,4,6]

then

filter()

[4,6]

MCQ 15

What is a pure function?

A.

Changes outside variables

B.

Always returns the same output for the same input

C.

Uses loops

D.

Uses objects


✅ Answer

B

Pure functions are predictable and easier to test.


MCQ 16

Which function is pure?

A.

let count = 0;

const add = () => {
  count++;
};

B.

const add = (a, b) => a + b;

C.

const add = () => Math.random();

D.

const add = () => Date.now();

✅ Answer

B

The same inputs always produce the same output, and it has no side effects.


MCQ 17

Find the bug.

const users = [
  { name: "Alice" }
];

const copy = users;

copy.push({
  name: "Bob"
});

console.log(users.length);

A.

1

B.

2

C.

Error

D.

undefined


✅ Answer

B

copy and users point to the same array.


MCQ 18

Better solution?

A.

const copy = users;

B.

const copy = [...users];

✅ Answer

B

This creates a new array.


MCQ 19

Output?

const products = [
  { price: 10 },
  { price: 20 }
];

const prices =
products.map(product => product.price);

console.log(prices);

A.

[10,20]

B.

[{price:10}]

C.

20

D.

Error


✅ Answer

A

map() extracts the price property from each object.


MCQ 20 (Hard)

Predict the output.

const users = [
  {
    id: 1,
    name: "Alice"
  },
  {
    id: 2,
    name: "Bob"
  }
];

const updatedUsers =
users.map(user =>
  user.id === 2
    ? {
        ...user,
        name: "John"
      }
    : user
);

console.log(updatedUsers);

A.

[
 {id:1,name:"Alice"},
 {id:2,name:"John"}
]

B.

[
 {id:1,name:"John"},
 {id:2,name:"John"}
]

C.

Original array

D.

Error


✅ Answer

A

This is one of the most common React patterns.

For each user:

  • If id === 2, return a new object with the updated name.

  • Otherwise, return the original user.


Common Beginner Mistakes

❌ Using push() instead of [...array, item]

❌ Using splice() instead of filter()

❌ Modifying objects directly

❌ Forgetting that map() returns a new array

❌ Using find() when you need filter()

❌ Copying arrays with = instead of [...]


Mini Coding Challenge

Question

Predict the output.

const products = [
  {
    id: 1,
    price: 100
  },
  {
    id: 2,
    price: 200
  },
  {
    id: 3,
    price: 300
  }
];

const updatedProducts =
products
  .filter(product => product.price >= 200)
  .map(product => ({
    ...product,
    price: product.price + 50
  }));

console.log(updatedProducts);
console.log(products);

✅ Answer

updatedProducts

[
  {
    id: 2,
    price: 250
  },
  {
    id: 3,
    price: 350
  }
]

products

[
  {
    id: 1,
    price: 100
  },
  {
    id: 2,
    price: 200
  },
  {
    id: 3,
    price: 300
  }
]

Why?

  1. filter() keeps products with price >= 200:

    [
      { id: 2, price: 200 },
      { id: 3, price: 300 }
    ]
    
  2. map() creates new objects and increases each price by 50.

  3. The original products array remains unchanged because both filter() and map() return new arrays, and { ...product } creates new objects.


Mini Project — React-style Shopping Cart Logic

Problem

Given:

const cart = [
  { id: 1, name: "Laptop", quantity: 1 },
  { id: 2, name: "Mouse", quantity: 2 },
  { id: 3, name: "Keyboard", quantity: 1 }
];

Perform these operations without changing the original cart:

  1. Add:

    { id: 4, name: "Monitor", quantity: 1 }
    
  2. Increase the quantity of the Mouse (id: 2) by 1.

  3. Remove the Keyboard (id: 3).

  4. Check if any item has quantity > 2.

  5. Check if every item has quantity >= 1.

  6. Create an array containing only the item names.


✅ One Possible Solution

const cart = [
  { id: 1, name: "Laptop", quantity: 1 },
  { id: 2, name: "Mouse", quantity: 2 },
  { id: 3, name: "Keyboard", quantity: 1 }
];

// 1. Add a new item
const cartWithMonitor = [
  ...cart,
  { id: 4, name: "Monitor", quantity: 1 }
];

// 2. Increase Mouse quantity
const updatedCart = cartWithMonitor.map(item =>
  item.id === 2
    ? {
        ...item,
        quantity: item.quantity + 1
      }
    : item
);

// 3. Remove Keyboard
const finalCart = updatedCart.filter(
  item => item.id !== 3
);

// 4. Any quantity > 2?
const hasLargeQuantity = finalCart.some(
  item => item.quantity > 2
);

// 5. Every quantity >= 1?
const allValid = finalCart.every(
  item => item.quantity >= 1
);

// 6. Get item names
const itemNames = finalCart.map(
  item => item.name
);

console.log(finalCart);
console.log(hasLargeQuantity);
console.log(allValid);
console.log(itemNames);

✅ Expected Output

[
  { id: 1, name: "Laptop", quantity: 1 },
  { id: 2, name: "Mouse", quantity: 3 },
  { id: 4, name: "Monitor", quantity: 1 }
]

true

true

[
  "Laptop",
  "Mouse",
  "Monitor"
]

🏆 The 8 React Patterns You Must Memorize

These are the patterns you'll write over and over in React:

// Add an item
const newArray = [...array, item];

// Remove an item
const newArray = array.filter(item => item.id !== id);

// Update an item
const newArray = array.map(item =>
  item.id === id
    ? { ...item, value: newValue }
    : item
);

// Find one item
const user = users.find(user => user.id === id);

// Check if any item matches
const exists = users.some(user => user.id === id);

// Check if all items match
const valid = users.every(user => user.active);

// Extract a property
const names = users.map(user => user.name);

// Copy an object with changes
const updatedUser = {
  ...user,
  age: 26
};

If these patterns become second nature, you'll find that React code is mostly combining them with React's APIs. Mastering these now will make your transition to React much smoother.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.