Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

React 5

 

Chapter 5 — Conditional Rendering

🎯 Goal

Learn how to show different UI based on different conditions.

This is one of the Top 5 most-used React skills in real projects.


First, one new idea (2 minutes)

Imagine you're entering a movie theater.

The security guard asks:

"Do you have a ticket?"

If Yes → Enter.

If No → Buy a ticket.

React does the same thing.

Instead of always showing the same UI, it decides what to show.

Condition
      │
      ▼
Is Logged In?
   │      │
 Yes      No
 │         │
Home     Login

New Syntax #1 — Ternary Operator

Instead of writing:

If condition is true
    show A
Else
    show B

React uses:

condition ? A : B

Think of it like:

Question ?

Yes Answer

:

No Answer

Example:

const isLoggedIn = true;

export default function Home() {
  return (
    <>
      {isLoggedIn ? <h1>Welcome</h1> : <h1>Please Login</h1>}
    </>
  );
}

New Syntax #2 — AND (&&)

Sometimes you only want to show something when a condition is true.

Example:

{isAdmin && <button>Delete User</button>}

Meaning:

If isAdmin is true

↓

Show button

Otherwise

↓

Show nothing

MCQs


Q1

Why do we use conditional rendering?

(A) To install packages

(B) To show different UI based on a condition

(C) To create folders

(D) To style components


Answer: (B)

Mini Explanation

Real apps don't always show the same screen.


Q2

Which syntax represents a ternary operator?

(A)

condition ? A : B

(B)

condition && A

(C)

condition || A

(D)

condition = A

Answer: (A)


Q3

Predict the output.

const isLoggedIn = true;

export default function Home() {
  return (
    <>
      {isLoggedIn ? <h1>Welcome</h1> : <h1>Login</h1>}
    </>
  );
}

(A) Welcome

(B) Login

(C) Both

(D) Error


Answer: (A)


Q4

Predict the output.

const isLoggedIn = false;

export default function Home() {
  return (
    <>
      {isLoggedIn ? <h1>Welcome</h1> : <h1>Login</h1>}
    </>
  );
}

(A) Welcome

(B) Login

(C) Both

(D) Error


Answer: (B)


Q5

Find the bug.

const isLoggedIn = true;

export default function Home() {
  return (
    <>
      {isLoggedIn ? <h1>Welcome</h1>}
    </>
  );
}

(A) No bug

(B) Missing : something

(C) Missing export

(D) Missing return


Answer: (B)

Mini Explanation

A ternary always needs both parts.

Correct:

isLoggedIn ? <h1>Welcome</h1> : <h1>Login</h1>

Q6

What does this display?

const isAdmin = true;

export default function Home() {
  return (
    <>
      {isAdmin && <button>Delete</button>}
    </>
  );
}

(A) Delete button

(B) Nothing

(C) Error

(D) undefined


Answer: (A)


Q7

Predict the output.

const isAdmin = false;

export default function Home() {
  return (
    <>
      {isAdmin && <button>Delete</button>}
    </>
  );
}

(A) Delete button

(B) Nothing

(C) Error

(D) undefined


Answer: (B)

Mini Explanation

&& only renders the right side when the left side is true.


Q8

Which code is better?

You only want to show a warning when isExpired is true.

(A)

isExpired
  ? <p>Expired</p>
  : null

(B)

isExpired && <p>Expired</p>

(C) Both work, but (B) is shorter and more common.

(D) Neither


Answer: (C)

Mini Explanation

Use && when there's nothing to show if the condition is false.


Q9

Predict the output.

const age = 20;

export default function Home() {
  return (
    <>
      {age >= 18 ? <h1>Adult</h1> : <h1>Child</h1>}
    </>
  );
}

(A) Adult

(B) Child

(C) Both

(D) Error


Answer: (A)


Q10

Find the bug.

const isAdmin = true;

export default function Home() {
  return (
    <>
      isAdmin && <button>Delete</button>
    </>
  );
}

(A) No bug

(B) Condition should be inside {}

(C) Missing export

(D) Missing button


Answer: (B)

Mini Explanation

JavaScript inside JSX must be wrapped in curly braces.

Correct:

{isAdmin && <button>Delete</button>}

Q11

Predict the output.

const stock = 0;

export default function Home() {
  return (
    <>
      {stock > 0
        ? <h2>In Stock</h2>
        : <h2>Out of Stock</h2>}
    </>
  );
}

(A) In Stock

(B) Out of Stock

(C) Error

(D) Both


Answer: (B)


Q12

Which statement is true?

(A) Ternary chooses between two UI options.

(B) && always shows both sides.

(C) JSX doesn't support conditions.

(D) React only supports if.


Answer: (A)


Q13

Predict the output.

const hasDiscount = true;

export default function Home() {
  return (
    <>
      <h1>Product</h1>
      {hasDiscount && <p>20% OFF</p>}
    </>
  );
}

(A) Product

(B) Product + 20% OFF

(C) 20% OFF only

(D) Error


Answer: (B)


Q14

Find the bug.

const isLoggedIn = false;

export default function Home() {
  return (
    <>
      {isLoggedIn ? <h1>Welcome</h1> <h1>Login</h1>}
    </>
  );
}

(A) No bug

(B) Missing :

(C) Missing return

(D) Missing export


Answer: (B)


Q15

Predict the output.

const score = 95;

export default function Home() {
  return (
    <>
      {score >= 50
        ? <h2>Pass</h2>
        : <h2>Fail</h2>}
    </>
  );
}

(A) Pass

(B) Fail

(C) Error

(D) Nothing


Answer: (A)


Q16

Interview Trap 🚨

Which code is cleaner when showing an "Admin Panel" only to admins?

(A)

isAdmin
  ? <AdminPanel />
  : null

(B)

isAdmin && <AdminPanel />

(C) Both work, but (B) is the pattern you'll see most often.

(D) Neither


Answer: (C)

Mini Explanation

When there's no "else" UI, && is simpler and easier to read.


Q17

Predict the output.

const premium = false;

export default function Home() {
  return (
    <>
      <h1>Dashboard</h1>
      {premium && <p>Premium Features</p>}
    </>
  );
}

(A) Dashboard

(B) Dashboard + Premium Features

(C) Premium Features

(D) Error


Answer: (A)


Q18 (Hard)

You're building an e-commerce website.

Which approach is best?

(A) Always display "Out of Stock"

(B)

product.inStock
  ? <button>Buy Now</button>
  : <button>Notify Me</button>

(C) Always display "Buy Now"

(D) Duplicate the page


Answer: (B)

Mini Explanation

Real apps change the UI based on data. If a product is available, users can buy it. Otherwise, they can ask to be notified.


⭐ Chapter Summary (The 20% You'll Use Every Day)

Remember these four patterns:

1. Show one of two options

condition ? A : B

Example:

isLoggedIn
  ? <HomePage />
  : <LoginPage />

2. Show something only when the condition is true

condition && A

Example:

isAdmin && <DeleteButton />

3. JavaScript inside JSX goes inside {}

{isLoggedIn ? <Home /> : <Login />}

4. Choose the right pattern

  • Two possible UIs → ? :

  • Show-or-hide UI → &&

This simple decision will help you write cleaner React code.


🎯 Mini Coding Challenge

Create these variables:

const isLoggedIn = true;
const isAdmin = false;

Requirements:

  • If the user is logged in, show:

Welcome Back

Otherwise:

Please Login
  • Show this button only if the user is an admin:

<button>Delete User</button>

Use both:

  • ? :

  • &&


🚀 Mini Real-World Project

Shopping Website

Create this data:

const products = [
  {
    name: "iPhone 16",
    price: "$999",
    inStock: true,
  },
  {
    name: "MacBook Air",
    price: "$1199",
    inStock: false,
  },
  {
    name: "AirPods Pro",
    price: "$249",
    inStock: true,
  },
];

Render the products using map().

For each product:

  • Show its name.

  • Show its price.

  • If inStock is true, display:

Buy Now

Otherwise display:

Out of Stock

This combines everything you've learned so far:

  • ✅ Components

  • ✅ Props

  • map()

  • ✅ Conditional Rendering


📈 Progress Check

You've now learned the core patterns that appear in almost every React/Next.js codebase:

  • ✅ Components

  • ✅ Props

  • ✅ Rendering Lists (map)

  • ✅ Conditional Rendering

These four concepts alone cover a large portion of everyday React UI work.

Next Chapter

When you reply "ok", we'll move to Chapter 6: Event Handling (onClick, onChange, onSubmit).

This is where your apps stop being static and start responding to user actions like button clicks, typing, and form submissions. It's a major step toward building interactive, real-world applications.

React 4

 

Chapter 4 — Rendering Lists with map()

🎯 Goal

Learn how to display many items using one component and one loop instead of writing the same code repeatedly.


First, one new idea (2 minutes)

Imagine you're writing the names of 100 students on certificates.

❌ Bad idea:

Rahul
Amit
Sara
Priya
...

(write each one manually)

✅ Better idea:

For every student,
print the student's name.

React works the same way.

Instead of writing:

<ProductCard name="iPhone" />
<ProductCard name="MacBook" />
<ProductCard name="AirPods" />

We usually store the data:

const products = [
  "iPhone",
  "MacBook",
  "AirPods"
];

Then generate the UI automatically.


New Syntax

const products = ["iPhone", "MacBook", "AirPods"];

products.map((product) => (
  <p>{product}</p>
));

What is map()?

Think of it like a photocopy machine.

Input:

Apple
Banana
Orange

Machine:

Wrap every fruit inside <p>

Output:

<p>Apple</p>
<p>Banana</p>
<p>Orange</p>

New Syntax Explained

products.map((product) => ...)
  • products → the array

  • .map() → visit every item

  • product → the current item

You can choose any name:

products.map((item) => ...)

or

products.map((fruit) => ...)

The name doesn't matter.


MCQs

Q1

Why do we use map() in React?

(A) To style components

(B) To display multiple items from an array

(C) To create folders

(D) To install packages


Answer: (B)

Mini Explanation

map() lets us generate UI for every item in an array.


Q2

Given:

const fruits = ["Apple", "Banana"];

Which code displays both fruits?

(A)

fruits.map((fruit) => <p>{fruit}</p>)

(B)

fruit.map((fruits) => <p>{fruit}</p>)

(C)

map(fruits)

(D)

<p>{fruits}</p>

Answer: (A)

Mini Explanation

Call map() on the array.


Q3

Predict the output.

const fruits = ["Apple", "Banana"];

export default function Home() {
  return (
    <>
      {fruits.map((fruit) => (
        <p>{fruit}</p>
      ))}
    </>
  );
}

(A) Apple Banana

(B) Apple

(C) Banana

(D) Error


Answer: (A)


Q4

How many <p> elements are created?

const colors = ["Red", "Blue", "Green"];
colors.map((color) => (
  <p>{color}</p>
));

(A) 1

(B) 2

(C) 3

(D) 4


Answer: (C)

Mini Explanation

One <p> is created for each item.


Q5

Predict the output.

const numbers = [10, 20];
numbers.map((number) => (
  <h1>{number}</h1>
));

(A) 10 20

(B) 1020

(C) Error

(D) Blank page


Answer: (A)


Q6

Find the bug.

const fruits = ["Apple", "Banana"];

export default function Home() {
  return (
    <>
      {fruit.map((fruit) => (
        <p>{fruit}</p>
      ))}
    </>
  );
}

(A) No bug

(B) Should use fruits.map(...)

(C) Missing return

(D) Missing export


Answer: (B)

Mini Explanation

The array is called fruits, not fruit.


Q7

Which variable represents the current item?

products.map((product) => ...)

(A) products

(B) map

(C) product

(D) None


Answer: (C)

Mini Explanation

product is the current item being processed.


Q8

Which code is better?

Option A

<ProductCard name="iPhone" />
<ProductCard name="MacBook" />
<ProductCard name="AirPods" />

Option B

products.map((product) => (
  <ProductCard name={product} />
))

(A) Option A

(B) Option B

(C) Both are equally good

(D) Neither


Answer: (B)

Mini Explanation

It scales easily. Add a new product to the array, and the UI updates automatically.


Q9

Predict the output.

const animals = ["Dog"];
animals.map((animal) => (
  <h2>{animal}</h2>
));

(A) Dog

(B) Dogs

(C) Error

(D) Nothing


Answer: (A)


Q10

Find the bug.

const fruits = ["Apple", "Banana"];

export default function Home() {
  return (
    <>
      {fruits.map((item) => (
        <p>{items}</p>
      ))}
    </>
  );
}

(A) No bug

(B) Should use {item}

(C) Missing export

(D) Missing map()


Answer: (B)

Mini Explanation

You named the variable item but tried to use items.

Names must match.


Q11

Predict the output.

const cities = ["Delhi", "Mumbai", "Pune"];
cities.map((city) => (
  <h3>{city}</h3>
));

(A) Delhi Mumbai Pune

(B) Delhi

(C) Pune

(D) Error


Answer: (A)


Q12

Which statement is true?

(A) map() only works with numbers.

(B) map() works with arrays.

(C) map() only works in Next.js.

(D) map() creates CSS.


Answer: (B)


Q13

Predict the output.

const names = [];
names.map((name) => (
  <p>{name}</p>
));

(A) Error

(B) Blank output

(C) undefined

(D) One empty paragraph


Answer: (B)

Mini Explanation

The array is empty, so there are no items to render.


Q14

Which is easier to maintain?

(A) Writing 100 <ProductCard /> components manually

(B) Storing products in an array and using map()

(C) Copying HTML repeatedly

(D) Creating one file per product


Answer: (B)


Q15

Predict the output.

const scores = [90, 80, 70];
scores.map((score) => (
  <p>{score}</p>
));

(A) 90 80 70

(B) 90

(C) Error

(D) Blank page


Answer: (A)


Q16

Interview Trap 🚨

Which code will produce a warning in React?

(A)

products.map((product) => (
  <p>{product}</p>
))

(B)

products.map((product) => (
  <p key={product}>{product}</p>
))

(C) Both

(D) Neither


Answer: (A)

Mini Explanation

When rendering a list, React expects a special prop called key.

Without it, you'll see a warning like:

"Each child in a list should have a unique 'key' prop."

For now, remember this rule:

Whenever you use map() to render a list, add a key.

Example:

products.map((product) => (
  <p key={product}>{product}</p>
));

We'll learn why React needs key in a later chapter.


Q17

Predict the output.

const books = ["Clean Code", "Deep Work"];
books.map((book) => (
  <h2>{book}</h2>
));

(A) Clean Code Deep Work

(B) Deep Work Clean Code

(C) Error

(D) One heading


Answer: (A)


Q18 (Hard)

You're building an e-commerce website with 5,000 products.

Which approach is better?

(A) Write 5,000 ProductCard components manually.

(B) Store the products in an array and use map().

(C) Create 5,000 pages with repeated HTML.

(D) Copy and paste each product.


Answer: (B)

Mini Explanation

This is exactly how real-world apps work. Product data comes from a database or API, and map() renders each item automatically.


⭐ Chapter Summary (The 20% You'll Use Every Day)

Remember these five patterns:

1. Store your data in an array.

const fruits = ["Apple", "Banana"];

2. Use map() to visit every item.

fruits.map((fruit) => ...)

3. Render JSX for each item.

fruits.map((fruit) => (
  <p>{fruit}</p>
));

4. Use {} to insert JavaScript values.

<p>{fruit}</p>

5. Add a key when rendering lists.

fruits.map((fruit) => (
  <p key={fruit}>{fruit}</p>
));

For now, just remember: List = map() + key.


🎯 Mini Coding Challenge

Create an array:

const skills = [
  "HTML",
  "CSS",
  "JavaScript",
  "React",
  "Next.js"
];

Display all the skills using map().

Bonus: Add a key to each rendered item.


🚀 Mini Real-World Project

Product Catalog

Create an array like this:

const products = [
  { name: "iPhone 16", price: "$999" },
  { name: "MacBook Air", price: "$1199" },
  { name: "AirPods Pro", price: "$249" }
];

Create a reusable ProductCard component that accepts:

  • name

  • price

Then use map() to render all the products.

Rule: Don't manually write three ProductCard components. Generate them from the array.


💡 One Important Note

This chapter introduced arrays, map(), and a small preview of key because these are among the most frequently used patterns in React.

In the next chapter, we'll combine what you've learned with Conditional Rendering—showing or hiding UI based on conditions (for example, "Show 'Out of Stock' only when a product isn't available"). This pattern appears in almost every production Next.js application.

Reply "ok" when you're ready for Chapter 5: Conditional Rendering.

React 3

 

Chapter 3 — Props (Making Components Dynamic)

🎯 Goal

Learn how to send data from one component to another so you can reuse the same component with different content.


First, one new idea (2 minutes)

Imagine a coffee shop.

There is one coffee machine (the component).

Customers place different orders:

  • Coffee → Latte

  • Coffee → Cappuccino

  • Coffee → Espresso

The machine is the same. Only the order changes.

Props work exactly like that.

Without props:

<Button />
<Button />
<Button />

All three buttons look exactly the same.

With props:

<Button text="Save" />
<Button text="Delete" />
<Button text="Cancel" />

Same component.
Different data.


New Syntax

Passing a prop

<Button text="Save" />

Here,

  • text → prop name

  • "Save" → value


Receiving a prop

function Button(props) {
  return <button>{props.text}</button>;
}

New Syntax Explained

You'll see curly braces {} inside JSX.

<button>{props.text}</button>

Think of it like saying:

"Insert the value of props.text here."

If props.text is "Save":

<button>Save</button>

MCQs

Q1

What is the main purpose of props?

(A) To style components

(B) To send data from one component to another

(C) To install packages

(D) To create folders


Answer: (B)

Mini Explanation

Props allow a parent component to send data to a child component.


Q2

Which code passes a prop?

(A)

<Button />

(B)

<Button text="Save" />

(C)

Button("Save")

(D)

<Button = "Save" />

Answer: (B)

Mini Explanation

Props are written like HTML attributes.


Q3

What will this display?

function Button(props) {
  return <button>{props.text}</button>;
}

export default function Home() {
  return <Button text="Save" />;
}

(A) Button

(B) Save

(C) props.text

(D) Error


Answer: (B)

Mini Explanation

props.text contains "Save".


Q4

Predict the output.

function Button(props) {
  return <button>{props.text}</button>;
}

export default function Home() {
  return (
    <>
      <Button text="Save" />
      <Button text="Delete" />
    </>
  );
}

(A) Save Delete

(B) Save Save

(C) Delete Delete

(D) Error


Answer: (A)

Mini Explanation

Each component receives its own prop value.


Q5

Find the bug.

function Button(props) {
  return <button>{props.title}</button>;
}

export default function Home() {
  return <Button text="Save" />;
}

(A) No bug

(B) Should use props.text

(C) Missing export

(D) Missing return


Answer: (B)

Mini Explanation

You passed text but tried to read title.

The names must match.


Q6

Which code is correct?

(A)

<Button text="Login" />

(B)

<Button("Login") />

(C)

<Button text=Login />

(D)

<Button:Login />

Answer: (A)

Mini Explanation

String values go inside quotes.


Q7

What will appear?

function Card(props) {
  return <h2>{props.title}</h2>;
}

export default function Home() {
  return <Card title="React" />;
}

(A) React

(B) title

(C) Card

(D) Error


Answer: (A)


Q8

Find the bug.

function Card(props) {
  return <h2>{props.name}</h2>;
}

export default function Home() {
  return <Card title="Next.js" />;
}

(A) Should use props.title

(B) Missing button

(C) Missing export

(D) No bug


Answer: (A)

Mini Explanation

The prop name is title, not name.


Q9

Predict the output.

function Welcome(props) {
  return <h1>Hello {props.name}</h1>;
}

export default function Home() {
  return <Welcome name="Pramod" />;
}

(A) Hello

(B) Hello Pramod

(C) Pramod

(D) Error


Answer: (B)


Q10

What happens here?

function Welcome(props) {
  return <h1>Hello {props.name}</h1>;
}

export default function Home() {
  return <Welcome />;
}

(A) Hello

(B) Hello undefined

(C) Error

(D) Blank page


Answer: (B)

Mini Explanation

No name prop was passed.

So props.name is undefined.


Q11

Which code is better?

Option A

<h2>Apple</h2>
<h2>Banana</h2>
<h2>Mango</h2>

Option B

<Fruit name="Apple" />
<Fruit name="Banana" />
<Fruit name="Mango" />

(A) Option A

(B) Option B

(C) Both

(D) Neither


Answer: (B)

Mini Explanation

Reusable components reduce repeated code.


Q12

Predict the output.

function Price(props) {
  return <p>${props.value}</p>;
}

export default function Home() {
  return (
    <>
      <Price value="100" />
      <Price value="250" />
    </>
  );
}

(A) $100 $250

(B) $100 $100

(C) $250 $250

(D) Error


Answer: (A)


Q13

Which statement is true?

(A) Props make components reusable.

(B) Props can only contain text.

(C) Props work only in Next.js pages.

(D) Props are used for CSS.


Answer: (A)

Mini Explanation

Props let one component display different data.


Q14

Find the bug.

function Button(props) {
  return <button>{props.text}</button>;
}

export default function Home() {
  return <Button Text="Save" />;
}

(A) No bug

(B) Should pass text, not Text

(C) Missing return

(D) Missing export


Answer: (B)

Mini Explanation

Prop names are case-sensitive.

text and Text are different.


Q15

Predict the output.

function Book(props) {
  return <h2>{props.title}</h2>;
}

export default function Home() {
  return (
    <>
      <Book title="Atomic Habits" />
      <Book title="Deep Work" />
      <Book title="Clean Code" />
    </>
  );
}

(A) One book

(B) Three book titles

(C) Error

(D) Blank page


Answer: (B)


Q16

Which is more reusable?

(A)

function Button() {
  return <button>Save</button>;
}

(B)

function Button(props) {
  return <button>{props.text}</button>;
}

(C) Both are equally reusable.

(D) Neither


Answer: (B)

Mini Explanation

The second component can display Save, Delete, Cancel, or anything else.


Q17

What will this display?

function User(props) {
  return <h2>{props.name}</h2>;
}

export default function Home() {
  return (
    <>
      <User name="Amit" />
      <User name="Sara" />
    </>
  );
}

(A) Amit Sara

(B) Sara Amit

(C) Amit Amit

(D) Error


Answer: (A)


Q18 (Hard)

You're building an online store.

Which approach is better?

(A) Create a different ProductCard component for every product.

(B) Create one ProductCard component and pass different props like name, price, and image.

(C) Copy and paste the HTML for every product.

(D) Create one page per product with repeated code.


Answer: (B)

Mini Explanation

Real-world apps reuse the same component with different props. This keeps your code clean and easy to update.


⭐ Chapter Summary (The 20% You'll Use Every Day)

Remember these four patterns:

1. Pass data

<Button text="Save" />

2. Receive data

function Button(props) {
  return <button>{props.text}</button>;
}

3. Use {} to display JavaScript values

<h1>{props.name}</h1>

4. Prop names must match exactly

✅ Correct:

<Button text="Save" />
props.text

❌ Wrong:

<Button Text="Save" />
props.text

🎯 Mini Coding Challenge

Create a reusable ProductCard component.

Requirements:

  • Accept these props:

    • name

    • price

Example:

<ProductCard name="iPhone 16" price="$999" />
<ProductCard name="MacBook Air" price="$1199" />
<ProductCard name="AirPods Pro" price="$249" />

Expected output:

iPhone 16
$999

MacBook Air
$1199

AirPods Pro
$249

🚀 Mini Real-World Project

Restaurant Menu

Build a simple restaurant menu using one reusable component.

Create a MenuItem component that accepts:

  • name

  • price

Use it like this:

<MenuItem name="Veg Burger" price="$5" />
<MenuItem name="Pizza" price="$12" />
<MenuItem name="Pasta" price="$10" />
<MenuItem name="Cold Coffee" price="$4" />

Rule: Don't create four different components. Build one reusable component and pass different props.


💡 Tiny Improvement for Future Chapters

From the next chapter onward, I'll also include "Interview Trap" questions—common mistakes that even junior developers make in real React/Next.js interviews (for example, confusing props with state, incorrect JSX syntax, or subtle rendering bugs). These are the kinds of questions that help you become job-ready, not just tutorial-ready.

Reply "ok" when you've finished this chapter, and we'll move on to Chapter 4: Rendering Lists with map(), where you'll learn one of the most frequently used patterns in production Next.js applications.

React 2

 

Chapter 2 — Components & JSX

🎯 Goal

Learn how to build reusable UI pieces (components) using JSX—the foundation of every Next.js app.


First, one new idea (2 minutes)

Imagine you're building a LEGO house.

Instead of building every window from scratch, you create one window and reuse it.

A component is exactly that—a reusable piece of UI.

Example:

function Button() {
  return <button>Save</button>;
}

Whenever you write:

<Button />

React displays:

<button>Save</button>

New Syntax

You'll see this syntax a lot:

<Button />

This is called using a component.

Notice:

  • HTML tags → lowercase (<button>, <div>)

  • Components → Capitalized (<Button />, <Navbar />)

That's one of the most common beginner mistakes.


MCQs

Q1

Which of these is a valid React component name?

(A) button
(B) navbar
(C) Navbar
(D) header-component

Answer: (C)

Mini Explanation:
React components should start with a capital letter.


Q2

Which syntax is used to render a component?

(A) <Navbar></Navbar> only

(B) <Navbar />

(C) Navbar()

(D) {Navbar}

Answer: (B)

Mini Explanation:
<Navbar /> is the standard JSX syntax. (<Navbar></Navbar> also works, but when there are no children, the self-closing form is preferred.)


Q3

Which tag is treated as an HTML element?

(A) <Button />

(B) <Navbar />

(C) <button>

(D) <Card />

Answer: (C)

Mini Explanation:
Lowercase tags are HTML.
Capitalized tags are React components.


Q4

What will this display?

export default function Home() {
  return <h1>Welcome</h1>;
}

(A) Welcome

(B) Error

(C) Blank page

(D) undefined

Answer: (A)

Mini Explanation:
The component returns an <h1>, so the page shows Welcome.


Q5

Which file usually contains reusable UI?

(A) public

(B) components

(C) node_modules

(D) styles

Answer: (B)

Mini Explanation:
Most Next.js projects keep reusable components inside the components folder.


Q6

What happens here?

function Button() {
  return <button>Save</button>;
}

export default function Home() {
  return <Button />;
}

(A) Save button appears

(B) Error

(C) Nothing

(D) undefined

Answer: (A)

Mini Explanation:
Home renders the Button component.


Q7

Find the bug.

function button() {
  return <button>Save</button>;
}

export default function Home() {
  return <button />;
}

(A) No bug

(B) Component name should start with a capital letter

(C) Button cannot return HTML

(D) Missing semicolon

Answer: (B)

Mini Explanation:
It should be:

function Button() {
  return <button>Save</button>;
}

Q8

Which code is better?

Option A

export default function Home() {
  return (
    <>
      <button>Save</button>
      <button>Cancel</button>
      <button>Delete</button>
    </>
  );
}

Option B

function Button() {
  return <button>Save</button>;
}

export default function Home() {
  return <Button />;
}

(A) Option A

(B) Option B

(C) Both are always equally good

(D) Neither

Answer: (B)

Mini Explanation:
Reusable components make your code easier to maintain.


Q9

Predict the output.

function Hello() {
  return <h2>Hello</h2>;
}

export default function Home() {
  return (
    <>
      <Hello />
      <Hello />
    </>
  );
}

(A) Hello

(B) Hello Hello

(C) Error

(D) Blank page

Answer: (B)

Mini Explanation:
Each <Hello /> renders once.


Q10

Find the bug.

function Navbar() {
  return <h1>Logo</h1>;
}

export default function Home() {
  return <navbar />;
}

(A) No bug

(B) Should be <Navbar />

(C) Should return <div>

(D) Missing export

Answer: (B)

Mini Explanation:
Lowercase names are treated as HTML tags, not components.


Q11

What will appear?

function Card() {
  return <p>React</p>;
}

export default function Home() {
  return (
    <>
      <h1>Course</h1>
      <Card />
    </>
  );
}

(A) Course

(B) React

(C) Course then React

(D) Error

Answer: (C)

Mini Explanation:
Both elements are rendered in order.


Q12

Find the bug.

function Card() {
}

(A) Missing return statement

(B) Missing import

(C) Missing export

(D) No bug

Answer: (A)

Mini Explanation:
Without return, nothing is rendered.


Q13

Predict the output.

function Welcome() {
  return <h2>Hi</h2>;
}

export default function Home() {
  return (
    <>
      <Welcome />
      <h1>Everyone</h1>
    </>
  );
}

(A) Hi Everyone

(B) Everyone Hi

(C) Error

(D) Only Hi

Answer: (A)

Mini Explanation:
JSX renders from top to bottom.


Q14

Which is the better file structure?

(A)

app/
  page.js
  Navbar.js
  Button.js
  Card.js

(B)

app/
  page.js

components/
  Navbar.js
  Button.js
  Card.js

(C) Both are equally preferred

(D) Put everything in public

Answer: (B)

Mini Explanation:
Keeping reusable components in a separate components folder keeps projects organized.


Q15

How many times is Button rendered?

function Button() {
  return <button>Buy</button>;
}

export default function Home() {
  return (
    <>
      <Button />
      <Button />
      <Button />
    </>
  );
}

(A) 1

(B) 2

(C) 3

(D) 0

Answer: (C)

Mini Explanation:
Every <Button /> creates one button.


Q16

Which statement is true?

(A) Components help reuse UI.

(B) Every page should copy and paste its HTML.

(C) Components can only be used once.

(D) Components only work with buttons.

Answer: (A)

Mini Explanation:
Reusability is one of the biggest advantages of React.


Q17

Predict the output.

function Title() {
  return <h1>Shop</h1>;
}

export default function Home() {
  return (
    <>
      <Title />
      <Title />
      <Title />
    </>
  );
}

(A) Shop

(B) Shop Shop

(C) Shop Shop Shop

(D) Error

Answer: (C)

Mini Explanation:
The component is rendered three times.


Q18 (Hard)

Which approach is better for a website with 100 pages using the same navigation bar?

(A) Copy the navbar into all 100 pages.

(B) Create one Navbar component and reuse it.

(C) Write the navbar inside public.

(D) Create 100 different navbars.

Answer: (B)

Mini Explanation:
One reusable component means one place to update. If you change the logo or add a menu item, every page gets the update automatically.


⭐ Chapter Summary (The 20% You'll Use Every Day)

Remember these four patterns:

  1. Capitalize component names.

function Navbar() {}
  1. Use components like HTML tags.

<Navbar />
  1. Keep reusable UI in components/.

  2. If you repeat UI, make it a component instead of copying and pasting.

If you remember just these four ideas, you'll understand a huge part of how React and Next.js apps are built.


🎯 Mini Coding Challenge

Create a project with this structure:

app/
  page.js

components/
  Header.js
  Footer.js

Requirements:

  • Header should display My Blog.

  • Footer should display © 2026 My Blog.

  • Render both components inside app/page.js.

Bonus: Add another component called Hero that displays:

Learn Next.js
Build Real Projects

🚀 Mini Real-World Project

Personal Portfolio Homepage

Build this page using only components.

Home Page
│
├── Header
├── Hero
├── Skills
├── Projects
└── Footer

Each section should be its own component stored in the components folder.

Rule: Do not copy HTML between sections. If something can become a reusable component, make it one.


Next Chapter Preview

When you reply "ok", we'll cover Props—the feature that lets components become dynamic instead of always displaying the same content. This is one of the biggest "aha!" moments in React and is used constantly in real-world Next.js projects.

React 1

Excellent. Based on your goal (building real projects → remote job), I would not teach Next.js the way most tutorials do.

Most courses spend hours on routing theory, rendering history, or obscure APIs. Instead, we'll learn the 20% of concepts you'll use in 80% of real projects.

Next.js Roadmap (Job-Oriented)

Phase 1 — JavaScript You'll Actually Need (Quick Revision)

Goal: Remove JS gaps that cause problems in Next.js.

  1. Modern ES6+

  2. Modules (import / export)

  3. Array methods (map, filter, find)

  4. Destructuring

  5. Spread operator

  6. Async / Await

  7. Fetch API

  8. Objects & Arrays

  9. Optional Chaining

  10. Template Literals


Phase 2 — React Essentials

Goal: Think in React.

  1. JSX

  2. Components

  3. Props

  4. Rendering Lists

  5. Conditional Rendering

  6. Events

  7. State (useState)

  8. Forms

  9. Effects (useEffect)

  10. Component Communication


Phase 3 — Next.js Core (Most Important)

This is where we'll spend most of our time.

  1. Creating a Next.js project

  2. App Router

  3. Pages

  4. Layouts

  5. Navigation

  6. Link

  7. Images

  8. Static Assets

  9. CSS Modules

  10. Tailwind CSS

  11. Server Components

  12. Client Components

  13. Fetching Data

  14. Loading UI

  15. Error UI

  16. Dynamic Routes

  17. Route Groups


Phase 4 — Real Backend Skills

  1. API Routes

  2. Route Handlers

  3. GET

  4. POST

  5. PUT

  6. DELETE

  7. Forms

  8. Validation

  9. Environment Variables


Phase 5 — Database

  1. Prisma

  2. PostgreSQL

  3. CRUD

  4. Relationships

  5. Migrations


Phase 6 — Authentication

  1. Login

  2. Register

  3. Sessions

  4. Protected Routes

  5. Middleware


Phase 7 — Production Skills

  1. File Upload

  2. Search

  3. Pagination

  4. Sorting

  5. Filtering

  6. Caching

  7. SEO

  8. Metadata

  9. Deployment (Vercel)

  10. Performance


Phase 8 — Portfolio Projects

We'll build progressively:

  • Notes App

  • Blog

  • Expense Tracker

  • Authentication System

  • Dashboard

  • Mini Ecommerce

  • Full Stack SaaS Clone


Learning Format

Every chapter will contain:

  • 🎯 Goal

  • 15–25 MCQs

  • Answers immediately after each question

  • Bug finding

  • Predict output

  • Better code choices

  • Mini challenge

  • Mini project


Chapter 1 — Modern Project Structure & Creating Your First Next.js App

🎯 Goal

Understand what a Next.js project looks like and identify the files you'll touch every day.

Assumption for this chapter: You already know basic HTML, CSS, and enough JavaScript to read simple examples. We'll fill any missing JS as we encounter it.


Q1 (Easy)

Which command creates a new Next.js project?

A)

npm create next-app

B)

npx create-next-app@latest

C)

next new app

D)

npm next install

✅ Answer

B

Why?

npx create-next-app@latest downloads and runs the latest project generator without installing it globally.


Q2

After creating the project, which command starts the development server?

A)

npm build

B)

npm start

C)

npm run dev

D)

next serve

✅ Answer

C

Why?

During development, you'll use:

npm run dev

Q3

Which folder contains your application pages when using the App Router?

A)

src

B)

public

C)

app

D)

styles

✅ Answer

C

Everything users visit begins inside the app folder.


Q4

You want an image like logo.png to be available at /logo.png in the browser.

Where should you place it?

A)

app

B)

public

C)

node_modules

D)

styles

✅ Answer

B

The public folder is for static files like images, PDFs, icons, and videos.


Q5

Which folder should you almost never edit manually?

A)

public

B)

node_modules

C)

app

D)

components

✅ Answer

B

It contains installed packages. Editing it is like changing the engine parts of a rented car—you'll lose those changes on reinstall.


Q6

What happens when you save a file while npm run dev is running?

A)

Restart your computer

B)

Nothing

C)

The browser usually updates automatically

D)

The project is deleted

✅ Answer

C

Next.js automatically reloads or refreshes the page.


Q7

Which file represents the homepage (/)?

A)

app/home/page.js

B)

app/index.js

C)

app/page.js

D)

pages/index.js

✅ Answer

C

app/page.js maps to the root URL /.


Q8

Suppose your project contains:

app
 ├── about
 │     page.js

Which URL opens it?

A)

/about

B)

/page

C)

/about/page

D)

/home

✅ Answer

A

Each folder becomes part of the URL, and page.js is the page for that folder.


Q9 — Predict the Output

app/page.js

export default function Home() {
  return <h1>Hello</h1>;
}

What appears?

A)

Nothing

B)

Hello

C)

Error

D)

undefined

✅ Answer

B

React renders the <h1> element.


Q10 — Find the Bug

function Home() {
    return <h1>Hello</h1>
}

What is missing?

A)

Nothing

B)

export default

C)

import React

D)

Semicolon

✅ Answer

B

A page component must be exported as the default export so Next.js can use it.

export default function Home() {
  return <h1>Hello</h1>;
}

New syntax: export default means "this is the main thing this file provides."


Q11

Which file is used to create a shared layout?

A)

layout.js

B)

template.js

C)

main.js

D)

wrapper.js

✅ Answer

A

layout.js wraps multiple pages so shared UI (like a navbar) doesn't have to be repeated.


Q12

Which folder usually stores reusable UI like buttons and cards?

A)

components

B)

public

C)

node_modules

D)

cache

✅ Answer

A

While optional, components is the common place for reusable pieces.


Q13 — Which Code Is Better?

Option A

function Home() {
  return <h1>Home</h1>;
}

export default Home;

Option B

export default function Home() {
  return <h1>Home</h1>;
}

✅ Answer

B

It's shorter and the style you'll see most often in real Next.js projects.


Q14 — Find the Bug

Project:

app
   about.js

Why doesn't /about work?

A)

Need CSS

B)

Should be:

app
   about
      page.js

C)

Need index.js

D)

Need main.js

✅ Answer

B

With the App Router, routes are folders containing a page.js file.


Q15 (Hardest)

Which structure creates both / and /products?

A)

app
   page.js
   products
      page.js

B)

pages
   index.js
   products.js

C)

src
   home.js

D)

routes
   products.js

✅ Answer

A

app/page.js serves /, and app/products/page.js serves /products.


🧠 Pattern to Remember

Think of the app folder like a building:

  • Every folder is a room (a URL segment).

  • Every page.js is the main activity in that room.

  • The layout.js is the hallway that connects rooms and stays the same as you move around.

Once you see this pattern, most routing in Next.js feels much simpler.


Mini Coding Challenge

Create this structure:

app
    page.js
    about
        page.js
    contact
        page.js

Display:

  • /Home

  • /aboutAbout Us

  • /contactContact

Try it yourself before checking the browser.


Mini Real-World Project

Company Website Skeleton

Using only today's concepts, create the basic structure for a small company website:

app
├── page.js          // Home
├── about
│   └── page.js
├── services
│   └── page.js
├── contact
│   └── page.js
├── layout.js
components
└── Navbar.js
public
└── logo.png

Your goals:

  • Create four pages.

  • Add a simple shared layout.

  • Create a reusable Navbar component (it can just display the company name for now).

  • Place a logo.png file in public so it's available later.


How we'll continue

When you reply with "ok", we'll move to Chapter 2: Components & JSX in Next.js, where you'll learn the most fundamental building block of every React/Next.js application through progressively harder MCQs, output prediction, bug-finding, and a mini project.

JS 27

Chapter 27 — Build Like a Professional

🎯 Goal (1 line)

Learn the habits and project structure that make your code look like it was written by a professional developer.

This chapter is less about new JavaScript and more about writing JavaScript that other developers enjoy working with. These habits are what interviewers and teammates notice.


The Professional Mindset

Instead of asking:

"Does it work?"

Start asking:

"Would I be happy maintaining this code six months from now?"


Rule #1: Write Small Functions

❌ Bad

const calculateOrder = (cart) => {
  // 100 lines of code
};

✅ Better

const calculateSubtotal = (cart) => {};
const calculateTax = (subtotal) => {};
const calculateTotal = (subtotal, tax) => {};

Small functions are:

  • Easier to test

  • Easier to debug

  • Easier to reuse


Rule #2: Use Meaningful Names

❌ Bad

const d = [];
const x = 100;
const a = user.name;

✅ Better

const products = [];
const taxRate = 100;
const userName = user.name;

Imagine a teammate reading your code.


Rule #3: Avoid Repeating Yourself (DRY)

❌ Bad

console.log("Welcome Alice");
console.log("Welcome Bob");
console.log("Welcome John");

✅ Better

const welcome = (name) => {
  console.log(`Welcome ${name}`);
};

welcome("Alice");
welcome("Bob");
welcome("John");

Rule #4: Keep Nesting Shallow

❌ Hard to Read

if (user) {
  if (user.isLoggedIn) {
    if (user.isAdmin) {
      console.log("Dashboard");
    }
  }
}

✅ Better

if (!user || !user.isLoggedIn || !user.isAdmin) {
  return;
}

console.log("Dashboard");

Rule #5: Use const by Default

Professional developers usually write:

const

until they actually need

let

Rule #6: Don't Modify Data Unnecessarily

user.name = "John";

const updatedUser = {
  ...user,
  name: "John"
};

This pattern is used constantly in React.


Rule #7: One Responsibility Per Function

const saveUser = () => {
  validate();
  save();
  sendEmail();
  updateUI();
};

const validateUser = () => {};
const saveUser = () => {};
const sendWelcomeEmail = () => {};
const updateUserInterface = () => {};

Rule #8: Keep Functions Pure When Possible

A pure function:

  • takes input

  • returns output

  • changes nothing outside

Good

const double = (number) => number * 2;

Avoid functions that secretly modify global variables.


Rule #9: Use Early Returns

Instead of:

if (user) {
  if (user.isLoggedIn) {
    console.log("Welcome");
  }
}

Write:

if (!user) return;

if (!user.isLoggedIn) return;

console.log("Welcome");

Much easier to scan.


Rule #10: Organize Files

Instead of:

project
    script.js

Prefer:

project
│
├── index.html
├── css
│     styles.css
│
├── js
│     app.js
│     api.js
│     utils.js
│
└── assets
      images

Rule #11: Comment WHY, Not WHAT

// Add two numbers
const total = a + b;

// Backend expects price including tax
const total = price + tax;

Code already explains what.

Comments explain why.


Rule #12: Consistent Formatting

Always indent consistently.

Bad:

if(user){

console.log(user)

}

Good:

if (user) {
  console.log(user);
}

Rule #13: Keep Logic Separate From UI

Instead of:

button.addEventListener("click", () => {
  const total = price * quantity;
  console.log(total);
});

Better:

const calculateTotal = (price, quantity) => price * quantity;

button.addEventListener("click", () => {
  console.log(calculateTotal(price, quantity));
});

Now calculateTotal() can be reused anywhere.


MCQs


Q1

Which variable name is better?

A.

const x = 500;

B.

const productPrice = 500;

✅ Answer

B

Meaningful names reduce confusion.


Q2

Which keyword should you use by default?

A. let

B. const

C. var

D. change


✅ Answer

B

Use const unless reassignment is needed.


Q3

Which function is easier to maintain?

A.

const process = () => {
  // 200 lines
};

B.

const validate = () => {};
const save = () => {};
const notify = () => {};

✅ Answer

B

Small functions are easier to understand and test.


Q4

Which follows the DRY principle?

A.

console.log("Hi Alice");
console.log("Hi Bob");

B.

const greet = (name) => {
  console.log(`Hi ${name}`);
};

✅ Answer

B

Write reusable code instead of repeating yourself.


Q5

Which is a pure function?

A.

let total = 0;

const add = (x) => {
  total += x;
};

B.

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

✅ Answer

B

It depends only on its inputs and has no side effects.


Q6

Which comment is more useful?

A.

// Increment i
i++;

B.

// Retry because the API sometimes returns temporary errors
retryCount++;

✅ Answer

B

Explain the reason, not the obvious.


Q7

Which structure is better?

A.

script.js

B.

js/
css/
assets/

✅ Answer

B

Projects grow. Organize early.


Q8

Find the issue.

const update = () => {
  validate();
  save();
  email();
  render();
  log();
  backup();
};

A. Too many responsibilities

B. Missing semicolon

C. Wrong keyword

D. Nothing


✅ Answer

A

One function should have one main job.


Q9

Which code is easier to read?

A.

const d = user.address.city;

B.

const userCity = user.address.city;

✅ Answer

B

Self-explanatory names reduce mental effort.


Q10

Predict the output.

const multiply = (a, b) => a * b;

console.log(multiply(4, 5));

A. 20

B. 45

C. undefined

D. Error


✅ Answer

A

The function returns 4 * 5.


Q11

Which update pattern is preferred in React?

A.

user.age = 30;

B.

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

✅ Answer

B

Create new objects instead of mutating existing ones.


Q12

Which function name is better?

A.

doStuff()

B.

calculateShippingCost()

✅ Answer

B

Names should describe exactly what the function does.


Q13

Which is easier to debug?

A.

One 300-line function.

B.

Ten small functions.


✅ Answer

B

Smaller units isolate problems.


Q14

Find the better version.

A.

if (user) {
  if (user.isAdmin) {
    dashboard();
  }
}

B.

if (!user) return;

if (!user.isAdmin) return;

dashboard();

✅ Answer

B

Early returns reduce nesting and improve readability.


Q15 (Hard)

Which code is more professional?

A

const calc = (a, b) => {
  let c = a * b;
  return c;
};

B

const calculateArea = (width, height) => width * height;

✅ Answer

B

Why?

  • Better function name

  • Better parameter names

  • Simpler implementation

  • No unnecessary variable


Mini Coding Challenge

Question

Refactor this code to make it more professional.

const x = (p, q) => {
  const r = p * q;
  console.log(r);
};

x(20, 5);

Pause before reading the solution.


✅ Answer

const calculateTotalPrice = (price, quantity) => {
  const total = price * quantity;
  console.log(total);
};

calculateTotalPrice(20, 5);

Improvements:

  • Function name explains its purpose.

  • Parameter names are meaningful.

  • Variable name (total) is descriptive.

  • Function call is more readable.


Final Mini Project — Product Inventory

Problem

Create a small inventory system.

Each product should have:

{
    id,
    name,
    price,
    stock
}

Tasks:

  1. Store three products in an array.

  2. Print all product names.

  3. Find a product by ID.

  4. Increase the stock of one product.

  5. Calculate the total inventory value (price × stock for each product).

  6. Keep your code clean by using small functions.


✅ One Possible Solution

const products = [
  { id: 1, name: "Laptop", price: 50000, stock: 2 },
  { id: 2, name: "Mouse", price: 800, stock: 10 },
  { id: 3, name: "Keyboard", price: 1500, stock: 5 }
];

const printProductNames = (items) => {
  items.forEach(product => console.log(product.name));
};

const findProductById = (items, id) => {
  return items.find(product => product.id === id);
};

const increaseStock = (items, id, amount) => {
  return items.map(product =>
    product.id === id
      ? { ...product, stock: product.stock + amount }
      : product
  );
};

const calculateInventoryValue = (items) => {
  return items.reduce(
    (total, product) => total + product.price * product.stock,
    0
  );
};

printProductNames(products);

const updatedProducts = increaseStock(products, 2, 5);

console.log(findProductById(updatedProducts, 2));

console.log(calculateInventoryValue(updatedProducts));

✅ Expected Output

Laptop
Mouse
Keyboard

{ id: 2, name: "Mouse", price: 800, stock: 15 }

123500

🎯 Professional Developer Checklist

Before you finish any feature, ask yourself:

  • ✅ Are my variable names meaningful?

  • ✅ Are my functions small (ideally under ~20 lines)?

  • ✅ Does each function have one responsibility?

  • ✅ Did I avoid repeating code?

  • ✅ Did I use const unless I needed let?

  • ✅ Did I avoid mutating objects/arrays when possible?

  • ✅ Is the code easy to read without extra comments?

  • ✅ Could another developer understand this in 2 minutes?

  • ✅ If I return to this code in 6 months, will I still understand it?

If you can consistently answer "yes" to these questions, you'll be writing code at a professional standard—not just code that works.

JS 26

Chapter 26 — Modern JavaScript Interview Questions

🎯 Goal (1 line)

Master the JavaScript concepts that frequently appear in frontend interviews and are useful in real-world development.

This chapter focuses on understanding behavior, not memorizing definitions.


MCQ 1 — Hoisting (Easy)

What will this output?

console.log(age);

let age = 25;

A. 25

B. undefined

C. Error

D. null


✅ Answer

C

Why?

let variables exist before they're declared, but you can't use them until the declaration line.


MCQ 2

What will this output?

sayHello();

function sayHello() {
  console.log("Hello");
}

A. Hello

B. Error

C. undefined

D. Nothing


✅ Answer

A

Why?

Function declarations are hoisted, so you can call them before they're defined.


MCQ 3

Predict the output.

const sayHello = () => {
  console.log("Hello");
};

sayHello();

A. Hello

B. Error

C. undefined

D. Nothing


✅ Answer

A

Arrow functions work normally after they are assigned.


MCQ 4

What happens?

sayHello();

const sayHello = () => {
  console.log("Hello");
};

A. Hello

B. undefined

C. Error

D. Nothing


✅ Answer

C

The variable sayHello hasn't been initialized yet.


MCQ 5 — this

What prints?

const user = {
  name: "Alice",

  greet() {
    console.log(this.name);
  }
};

user.greet();

A. Alice

B. undefined

C. Error

D. user


✅ Answer

A

Inside an object method, this refers to the object before the dot (user).


MCQ 6

Predict the output.

const user = {
  name: "Alice",

  greet: () => {
    console.log(this.name);
  }
};

user.greet();

A. Alice

B. undefined

C. Error

D. user


✅ Answer

B

Arrow functions don't have their own this. They use the surrounding this, which is not user here.

Rule: Avoid arrow functions for object methods if you need this.


MCQ 7

Which method is better?

A.

const user = {
  greet: () => {}
};

B.

const user = {
  greet() {}
};

✅ Answer

B

Object methods should usually use the method syntax (or regular functions), not arrow functions.


MCQ 8 — Closures

What prints?

function outer() {
  let count = 0;

  return () => {
    count++;
    console.log(count);
  };
}

const counter = outer();

counter();
counter();
counter();

A.

1
2
3

B.

1
1
1

C.

3
3
3

D. Error


✅ Answer

A

The returned function remembers the count variable even after outer() finishes.

This is called a closure.

Think of it like carrying a backpack with the variables you need.


MCQ 9

How many different count variables exist here?

const a = outer();
const b = outer();

A. 1

B. 2

C. 0

D. 3


✅ Answer

B

Each call to outer() creates a brand-new private count.


MCQ 10 — Shallow Copy

Output?

const user = {
  profile: {
    age: 20
  }
};

const copy = { ...user };

copy.profile.age = 30;

console.log(user.profile.age);

A. 20

B. 30

C. undefined

D. Error


✅ Answer

B

Spread creates only a shallow copy.

Nested objects remain shared.


MCQ 11

Which makes a new top-level object?

A.

const copy = user;

B.

const copy = { ...user };

C.

Both

D.

Neither


✅ Answer

B

user and copy become different top-level objects.


MCQ 12 — call()

Predict the output.

const user = {
  name: "Alice"
};

function greet() {
  console.log(this.name);
}

greet.call(user);

A. Alice

B. undefined

C. Error

D. user


✅ Answer

A

call() lets you choose what this should be.


MCQ 13

What prints?

function add(a, b) {
  console.log(a + b);
}

add.call(null, 2, 3);

A. 23

B. 5

C. Error

D. undefined


✅ Answer

B

call() passes arguments one by one.


MCQ 14 — apply()

What is different?

add.apply(null, [2, 3]);

A. Same as call, but arguments are passed as an array.

B. Faster.

C. Doesn't use this.

D. Deprecated.


✅ Answer

A

apply() expects an array of arguments.


MCQ 15 — bind()

Output?

const user = {
  name: "Bob"
};

function greet() {
  console.log(this.name);
}

const hello = greet.bind(user);

hello();

A. Bob

B. undefined

C. Error

D. user


✅ Answer

A

bind() returns a new function with this permanently set.


MCQ 16 — Debouncing

A search box should wait until the user stops typing before making one API request.

Which technique?

A. Throttling

B. Debouncing

C. Closure

D. Hoisting


✅ Answer

B

Debouncing waits for inactivity before running the function.

Example: Search suggestions.


MCQ 17 — Throttling

A button should trigger at most once every second, even if clicked 100 times.

Which technique?

A. Debouncing

B. Closure

C. Throttling

D. Binding


✅ Answer

C

Throttling limits how often a function can run.

Example: Scroll events.


MCQ 18 — Event Loop

Predict the output.

console.log("A");

setTimeout(() => {
  console.log("B");
}, 0);

console.log("C");

A.

A
B
C

B.

A
C
B

C.

B
A
C

D. Error


✅ Answer

B

Even with 0 ms, setTimeout runs after the current synchronous code finishes.


MCQ 19

Output?

console.log(1);

Promise.resolve().then(() => {
  console.log(2);
});

console.log(3);

A.

1
2
3

B.

1
3
2

C.

2
1
3

D. Error


✅ Answer

B

Promise callbacks run before timers, but after the current synchronous code.

Order:

1 → 3 → 2


MCQ 20 (Hard)

Predict the output.

console.log("Start");

setTimeout(() => {
  console.log("Timeout");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");

A.

Start
Timeout
Promise
End

B.

Start
End
Timeout
Promise

C.

Start
End
Promise
Timeout

D.

Promise
Start
End
Timeout

✅ Answer

C

Execution order:

  1. Start

  2. End

  3. Promise callback (microtask)

  4. Timer callback (macrotask)

Output:

Start
End
Promise
Timeout

Common Beginner Mistakes

❌ Calling arrow functions before they are assigned.

❌ Using arrow functions as object methods when you need this.

❌ Thinking { ...obj } deep-copies nested objects.

❌ Confusing call(), apply(), and bind().

❌ Thinking setTimeout(..., 0) runs immediately.

❌ Thinking Promises and setTimeout have the same priority.


Mini Coding Challenge

Question

Without running the code, predict the output:

function createCounter() {
  let count = 0;

  return () => {
    count++;
    return count;
  };
}

const counter1 = createCounter();
const counter2 = createCounter();

console.log(counter1());
console.log(counter1());
console.log(counter2());
console.log(counter1());

Pause and think before checking.


✅ Answer

Output:

1
2
1
3

Why?

  • counter1 has its own private count.

  • counter2 has a separate private count.

  • They don't share state.

Step by step:

  • counter1() → 1

  • counter1() → 2

  • counter2() → 1 (new closure)

  • counter1() → 3


Mini Project — Rate-Limited Click Logger

Problem

Create a button that logs "Clicked!" to the console, but only once every 2 seconds, no matter how many times the user clicks it.

This demonstrates throttling.

One Possible Solution

let canClick = true;

const button = document.querySelector("button");

button.addEventListener("click", () => {
  if (!canClick) return;

  console.log("Clicked!");

  canClick = false;

  setTimeout(() => {
    canClick = true;
  }, 2000);
});

How it works

  • First click logs "Clicked!".

  • Further clicks within 2 seconds are ignored.

  • After 2 seconds, clicking works again.


🎯 Chapter 26 — The 20% That Gives You 80%

These are the interview topics worth mastering:

  1. Closures: Functions remember variables from where they were created.

  2. Hoisting: Function declarations are hoisted; let/const cannot be used before declaration.

  3. this: In object methods, use regular methods/functions—not arrow functions—when you need this.

  4. Shallow vs. Deep Copy: { ...obj } copies only the first level.

  5. call() / apply() / bind():

    • call(obj, a, b) → invoke immediately with separate arguments.

    • apply(obj, [a, b]) → invoke immediately with an array.

    • bind(obj) → return a new function with this fixed.

  6. Event Loop:

    • Synchronous code runs first.

    • Promise callbacks (microtasks) run next.

    • setTimeout callbacks (macrotasks) run afterward.

  7. Debounce vs. Throttle:

    • Debounce: Wait until the user stops triggering the event (e.g., search input).

    • Throttle: Limit how often an action can occur (e.g., scroll or resize handlers).

These concepts appear repeatedly in frontend interviews and help explain many "why did JavaScript do that?" moments in real applications.

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.