0% found this document useful (0 votes)
3 views25 pages

Coding Questions

This document provides a comprehensive set of 60 technical test questions for junior developers focusing on the MERN stack, categorized into JavaScript Fundamentals, MongoDB Schema Design, React, and Problem-Solving. It includes strategies for approaching the test, such as understanding questions, breaking down problems, and optimizing code. Each category contains practical coding challenges and theoretical concepts relevant to the MERN stack technologies.

Uploaded by

bc210415570
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views25 pages

Coding Questions

This document provides a comprehensive set of 60 technical test questions for junior developers focusing on the MERN stack, categorized into JavaScript Fundamentals, MongoDB Schema Design, React, and Problem-Solving. It includes strategies for approaching the test, such as understanding questions, breaking down problems, and optimizing code. Each category contains practical coding challenges and theoretical concepts relevant to the MERN stack technologies.

Uploaded by

bc210415570
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MERN Stack Technical Test Questions for Junior

Developers

Grok 3

July 2025

Contents
1 Introduction 3

2 Strategy for Solving MERN Stack Written Test Questions 3

3 JavaScript Fundamentals 3
3.1 Question 1: Reverse a String . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.2 Question 2: Find the Longest Word . . . . . . . . . . . . . . . . . . . . . 4
3.3 Question 3: Check if a String is a Palindrome . . . . . . . . . . . . . . . 4
3.4 Question 4: Remove Duplicates from an Array . . . . . . . . . . . . . . . 4
3.5 Question 5: Check if Two Strings are Anagrams . . . . . . . . . . . . . . 4
3.6 Question 6: Count Vowels in a String . . . . . . . . . . . . . . . . . . . . 4
3.7 Question 7: Find the Largest Number in an Array . . . . . . . . . . . . . 5
3.8 Question 8: Check if a Number is Prime . . . . . . . . . . . . . . . . . . 5
3.9 Question 9: Calculate Factorial of a Number . . . . . . . . . . . . . . . . 5
3.10 Question 10: Remove Whitespace from a String . . . . . . . . . . . . . . 5
3.11 Question 11: Capitalize First Letter of Each Word . . . . . . . . . . . . . 6
3.12 Question 12: Check if String Contains Only Digits . . . . . . . . . . . . 6
3.13 Question 13: Sum Numbers in an Array . . . . . . . . . . . . . . . . . . 6
3.14 Question 14: Convert String to camelCase . . . . . . . . . . . . . . . . . 6
3.15 Question 15: Find Array Intersection . . . . . . . . . . . . . . . . . . . . 7

4 MongoDB Schema Design 7


4.1 Question 16: Design a Blog Schema . . . . . . . . . . . . . . . . . . . . . 7
4.2 Question 17: Find Posts by User . . . . . . . . . . . . . . . . . . . . . . 7
4.3 Question 18: Add a Comment to a Post . . . . . . . . . . . . . . . . . . 8
4.4 Question 19: Create an Index on Email . . . . . . . . . . . . . . . . . . . 8
4.5 Question�noitseuQ 20: Update a Post’s Title . . . . . . . . . . . . . . . . 8
4.6 Question 21: Design an E-commerce Product Schema . . . . . . . . . . . 9
4.7 Question 22: Find Products by Category . . . . . . . . . . . . . . . . . . 9
4.8 Question 23: Delete a Post . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.9 Question 24: Count Posts per User . . . . . . . . . . . . . . . . . . . . . 10
4.10 Question 25: Create a Compound Index . . . . . . . . . . . . . . . . . . 10
4.11 Question 26: Design a Shopping Cart Schema . . . . . . . . . . . . . . . 10

1
4.12 Question 27: Add Item to Cart . . . . . . . . . . . . . . . . . . . . . . . 11
4.13 Question 28: Calculate Cart Total . . . . . . . . . . . . . . . . . . . . . . 11
4.14 Question 29: Remove Item from Cart . . . . . . . . . . . . . . . . . . . . 12
4.15 Question 30: Create Cart Index . . . . . . . . . . . . . . . . . . . . . . . 12

5 React 12
5.1 Question 31: Counter Component . . . . . . . . . . . . . . . . . . . . . . 12
5.2 Question 32: Fetch and Display Data . . . . . . . . . . . . . . . . . . . . 13
5.3 Question 33: Controlled Input Component . . . . . . . . . . . . . . . . . 14
5.4 Question 34: Pass Props to Child Component . . . . . . . . . . . . . . . 14
5.5 Question 35: Auto-Focus Input . . . . . . . . . . . . . . . . . . . . . . . 14
5.6 Question 36: Toggle Button Component . . . . . . . . . . . . . . . . . . 15
5.7 Question 37: Theme Switching with Context API . . . . . . . . . . . . . 15
5.8 Question 38: Form Submission . . . . . . . . . . . . . . . . . . . . . . . 16
5.9 Question 39: Dynamic List Rendering . . . . . . . . . . . . . . . . . . . 17
5.10 Question 40: Update Document Title . . . . . . . . . . . . . . . . . . . . 17
5.11 Question 41: Toggle Visibility . . . . . . . . . . . . . . . . . . . . . . . . 18
5.12 Question 42: Deletable List . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.13 Question 43: Timer Component . . . . . . . . . . . . . . . . . . . . . . . 19
5.14 Question 44: Multiple Input Form . . . . . . . . . . . . . . . . . . . . . . 19
5.15 Question 45: Conditional Rendering . . . . . . . . . . . . . . . . . . . . 20

6 Problem-Solving 20
6.1 Question 46: Second Largest Number . . . . . . . . . . . . . . . . . . . . 20
6.2 Question 47: Balanced Parentheses . . . . . . . . . . . . . . . . . . . . . 20
6.3 Question 48: Fibonacci Sequence . . . . . . . . . . . . . . . . . . . . . . 21
6.4 Question 49: Create Product Route . . . . . . . . . . . . . . . . . . . . . 21
6.5 Question 50: Reverse Words in a Sentence . . . . . . . . . . . . . . . . . 22
6.6 Question 51: First Non-Repeating Character . . . . . . . . . . . . . . . . 22
6.7 Question 52: Filter List Component . . . . . . . . . . . . . . . . . . . . . 22
6.8 Question 53: Merge Sorted Arrays . . . . . . . . . . . . . . . . . . . . . 23
6.9 Question 54: Request Logger Middleware . . . . . . . . . . . . . . . . . . 23
6.10 Question 55: Power of Two . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.11 Question 56: Rotate Array . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.12 Question 57: Longest Common Prefix . . . . . . . . . . . . . . . . . . . . 24
6.13 Question 58: Valid Email . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.14 Question 59: Products by Price Range . . . . . . . . . . . . . . . . . . . 24
6.15 Question 60: Two Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2
1 Introduction
This document contains 60 questions and answers for a MERN stack technical test,
designed for candidates with approximately one year of experience. The questions are
divided into four categories: JavaScript Fundamentals, MongoDB Schema Design, React,
and Problem-Solving. Each category includes 15 questions, covering practical coding,
theoretical concepts, and problem-solving skills relevant to the MERN stack (MongoDB,
[Link], React, [Link]). A strategy for approaching the test is also provided.

2 Strategy for Solving MERN Stack Written Test


Questions
• Understand the Question: Identify inputs, outputs, and constraints. Clarify
edge cases (e.g., empty strings, negative numbers).
• Break Down the Problem: Use pseudocode or comments to outline steps before
coding.
• Choose the Right Tools: Use JavaScript array methods, React hooks, and Mon-
goose for MongoDB queries.
• Handle Edge Cases: Check for null, undefined, or empty inputs.
• Optimize and Test: Aim for efficient code (e.g., O(n) complexity) and test with
sample inputs.
• Time Management: Allocate time based on complexity (e.g., 5 minutes for simple
questions, 10 for complex ones).
• Think Aloud: Comment code to explain logic, demonstrating problem-solving
skills.
• Practice Patterns: Master string/array manipulation, MongoDB CRUD, and
React hooks.
• Review and Debug: Check syntax, query optimization, and state management.
• Stay Calm: Approach unfamiliar questions systematically, leveraging your expe-
rience.

3 JavaScript Fundamentals
3.1 Question 1: Reverse a String
Write a function to reverse a string.
1 function reverseString (str) {
2 if (! str) return "";
3 return str. split (''). reverse ().join ('');
4 }
5 console .log( reverseString (" hello ")); // Output : " olleh "
6 console .log( reverseString ("")); // Output : ""

3
3.2 Question 2: Find the Longest Word
Write a function to find the longest word in a sentence.
1 function longestWord ( sentence ) {
2 if (! sentence ) return "";
3 return sentence . split (' '). reduce (( longest , current ) =>
4 current . length > longest . length ? current : longest , '');
5 }
6 console .log( longestWord ("I love coding very much ")); // Output : "
coding "

3.3 Question 3: Check if a String is a Palindrome


Write a function to check if a string is a palindrome.
1 function isPalindrome (str) {
2 const cleanStr = str. toLowerCase (). replace (/[^a-z0 -9]/g, '');
3 return cleanStr === cleanStr . split (''). reverse ().join ('');
4 }
5 console .log( isPalindrome ("A man a plan a canal Panama ")); // Output :
true

3.4 Question 4: Remove Duplicates from an Array


Write a function to remove duplicate elements from an array.
1 function removeDuplicates (arr) {
2 return [... new Set(arr)];
3 }
4 console .log( removeDuplicates ([1 , 2, 2, 3, 4, 4, 5])); // Output : [1,
2, 3, 4, 5]

3.5 Question 5: Check if Two Strings are Anagrams


Write a function to check if two strings are anagrams.
1 function areAnagrams (str1 , str2) {
2 const cleanStr1 = str1. toLowerCase (). replace (/[^a-z0 -9]/g, '').
split ('').sort ().join ('');
3 const cleanStr2 = str2. toLowerCase (). replace (/[^a-z0 -9]/g, '').
split ('').sort ().join ('');
4 return cleanStr1 === cleanStr2 ;
5 }
6 console .log( areAnagrams (" listen ", " silent ")); // Output : true

3.6 Question 6: Count Vowels in a String


Write a function to count the number of vowels in a string.

4
1 function countVowels (str) {
2 const vowels = ['a', 'e', 'i', 'o', 'u '];
3 return str. toLowerCase (). split (''). filter (char => vowels .
includes (char)). length ;
4 }
5 console .log( countVowels (" hello world ")); // Output : 3

3.7 Question 7: Find the Largest Number in an Array


Write a function to find the largest number in an array.
1 function findLargest (arr) {
2 if (! arr. length ) return null;
3 return [Link] (... arr);
4 }
5 console .log( findLargest ([3 , 1, 4, 1, 5, 9, 2])); // Output : 9

3.8 Question 8: Check if a Number is Prime


Write a function to check if a number is prime.
1 function isPrime (num) {
2 if (num <= 1) return false ;
3 for (let i = 2; i <= [Link](num); i++) {
4 if (num % i === 0) return false ;
5 }
6 return true;
7 }
8 console .log( isPrime (17)); // Output : true

3.9 Question 9: Calculate Factorial of a Number


Write a function to calculate the factorial of a number.
1 function factorial (n) {
2 if (n < 0) return -1;
3 if (n === 0 || n === 1) return 1;
4 return n * factorial (n - 1);
5 }
6 console .log( factorial (5)); // Output : 120

3.10 Question 10: Remove Whitespace from a String


Write a function to remove all whitespace from a string.
1 function removeWhitespace (str) {
2 return str. replace (/\s/g, '');
3 }
4 console .log( removeWhitespace (" Hello World !")); // Output : "
HelloWorld !"

5
3.11 Question 11: Capitalize First Letter of Each Word
Write a function to capitalize the first letter of each word in a string.
1 function capitalizeWords (str) {
2 if (! str) return "";
3 return str. split (' ').map(word =>
4 word. charAt (0). toUpperCase () + word. slice (1). toLowerCase ()
5 ).join(' ');
6 }
7 console .log( capitalizeWords (" hello world ")); // Output : " Hello World
"

3.12 Question 12: Check if String Contains Only Digits


Write a function to check if a string contains only digits.
1 function isDigitsOnly (str) {
2 return /^\d+$/. test(str);
3 }
4 console .log( isDigitsOnly ("12345") ); // Output : true
5 console .log( isDigitsOnly ("12 a34 ")); // Output : false

3.13 Question 13: Sum Numbers in an Array


Write a function to sum all numbers in an array, ignoring non-numbers.
1 function sumNumbers (arr) {
2 return arr. filter (item => typeof item === 'number ' && ! isNaN (
item))
3 . reduce ((sum , num) => sum + num , 0);
4 }
5 console .log( sumNumbers ([1 , "2" , 3, null , 4])); // Output : 8

3.14 Question 14: Convert String to camelCase


Write a function to convert a string to camelCase.
1 function toCamelCase (str) {
2 return str. toLowerCase ()
3 . split (' ')
4 .map (( word , index ) =>
5 index === 0 ? word : word. charAt (0). toUpperCase ()
+ word. slice (1)
6 )
7 .join ('');
8 }
9 console .log( toCamelCase (" hello world ")); // Output : " helloWorld "

6
3.15 Question 15: Find Array Intersection
Write a function to find the intersection of two arrays.
1 function arrayIntersection (arr1 , arr2) {
2 const set = new Set(arr2);
3 return [... new Set(arr1. filter (item => [Link](item)))];
4 }
5 console .log( arrayIntersection ([1 , 2, 3, 4], [2, 4, 6])); // Output :
[2, 4]

4 MongoDB Schema Design


4.1 Question 16: Design a Blog Schema
Design a MongoDB schema for a blog application with users, posts, and comments.
1 const mongoose = require ('mongoose ');
2

3 const userSchema = new mongoose . Schema ({


4 username : { type: String , required : true , unique : true },
5 email : { type: String , required : true , unique : true },
6 password : { type: String , required : true },
7 createdAt : { type: Date , default : [Link] }
8 });
9

10 const postSchema = new mongoose . Schema ({


11 title : { type: String , required : true },
12 content : { type: String , required : true },
13 author : { type: mongoose . Schema . Types .ObjectId , ref: 'User ',
required : true },
14 comments : [{
15 content : { type: String , required : true },
16 author : { type: mongoose . Schema .Types .ObjectId , ref: 'User '
},
17 createdAt : { type: Date , default : [Link] }
18 }],
19 createdAt : { type: Date , default : [Link] }
20 });
21

22 const User = mongoose . model ('User ', userSchema );


23 const Post = mongoose . model ('Post ', postSchema );

4.2 Question 17: Find Posts by User


Write a query to find posts by a specific user.
1 const mongoose = require ('mongoose ');
2 const Post = require ( './ models /Post ');
3

4 async function findPostsByUser ( userId ) {

7
5 try {
6 const posts = await [Link] ({ author : userId }). populate ('
author ', 'username ');
7 return posts;
8 } catch ( error ) {
9 console .error (' Error fetching posts :', error );
10 throw error;
11 }
12 }

4.3 Question 18: Add a Comment to a Post


Write a function to add a comment to a post.
1 const mongoose = require ('mongoose ');
2 const Post = require ( './ models /Post ');
3

4 async function addComment (postId , content , authorId ) {


5 try {
6 const post = await Post. findByIdAndUpdate (
7 postId ,
8 { $push: { comments : { content , author : authorId ,
createdAt : new Date () } } },
9 { new: true }
10 );
11 return post;
12 } catch ( error ) {
13 console .error (' Error adding comment :', error );
14 throw error;
15 }
16 }

4.4 Question 19: Create an Index on Email


Create an index on the email field of the User collection.
1 db. users . createIndex ({ email : 1 });

4.5 Question�noitseuQ 20: Update a Post’s Title


Write a query to update a post’s title.
1 const mongoose = require ('mongoose ');
2 const Post = require ( './ models /Post ');
3

4 async function updatePostTitle (postId , newTitle ) {


5 try {
6 const post = await Post. findByIdAndUpdate (
7 postId ,
8 { title: newTitle },

8
9 { new: true }
10 );
11 return post;
12 } catch ( error ) {
13 console .error (' Error updating post:', error );
14 throw error;
15 }
16 }

4.6 Question 21: Design an E-commerce Product Schema


Design a schema for an e-commerce product catalog.
1 const mongoose = require ('mongoose ');
2

3 const categorySchema = new mongoose . Schema ({


4 name: { type: String , required : true , unique : true }
5 });
6

7 const productSchema = new mongoose . Schema ({


8 name: { type: String , required : true },
9 price : { type: Number , required : true , min: 0 },
10 stock : { type: Number , required : true , min: 0 },
11 category : { type: mongoose . Schema . Types .ObjectId , ref: 'Category
', required : true },
12 createdAt : { type: Date , default : [Link] }
13 });
14

15 const Category = mongoose . model ('Category ', categorySchema );


16 const Product = mongoose . model ('Product ', productSchema );

4.7 Question 22: Find Products by Category


Write a query to find products by category.
1 const mongoose = require ('mongoose ');
2 const Product = require ( './ models /Product ');
3

4 async function findProductsByCategory ( categoryId ) {


5 try {
6 const products = await Product .find ({ category : categoryId
}). populate ('category ', 'name ');
7 return products ;
8 } catch ( error ) {
9 console .error (' Error fetching products :', error );
10 throw error;
11 }
12 }

9
4.8 Question 23: Delete a Post
Write a function to delete a post.
1 const mongoose = require ('mongoose ');
2 const Post = require ( './ models /Post ');
3

4 async function deletePost ( postId ) {


5 try {
6 const post = await Post. findByIdAndDelete ( postId );
7 return post;
8 } catch ( error ) {
9 console .error (' Error deleting post:', error );
10 throw error;
11 }
12 }

4.9 Question 24: Count Posts per User


Write an aggregation query to count posts per user.
1 const mongoose = require ('mongoose ');
2 const Post = require ( './ models /Post ');
3

4 async function countPostsPerUser () {


5 try {
6 const result = await Post. aggregate ([
7 { $group : { _id: '$author ', postCount : { $sum: 1 } } },
8 { $lookup : { from: 'users ', localField : '_id ',
foreignField : '_id ', as: 'author ' } },
9 { $unwind : '$author ' },
10 { $project : { username : '$author .username ', postCount : 1
} }
11 ]);
12 return result ;
13 } catch ( error ) {
14 console .error (' Error counting posts :', error );
15 throw error;
16 }
17 }

4.10 Question 25: Create a Compound Index


Create a compound index for efficient post searches.
1 db. posts . createIndex ({ title : 1, createdAt : -1 });

4.11 Question 26: Design a Shopping Cart Schema


Design a schema for a user’s shopping cart.

10
1 const mongoose = require ('mongoose ');
2

3 const cartSchema = new mongoose . Schema ({


4 user: { type: mongoose . Schema . Types .ObjectId , ref: 'User ',
required : true },
5 items : [{
6 product : { type: mongoose . Schema . Types .ObjectId , ref: '
Product ', required : true },
7 quantity : { type: Number , required : true , min: 1 }
8 }],
9 updatedAt : { type: Date , default : [Link] }
10 });
11

12 const Cart = mongoose . model ('Cart ', cartSchema );

4.12 Question 27: Add Item to Cart


Write a query to add an item to a user’s cart.
1 const mongoose = require ('mongoose ');
2 const Cart = require ( './ models /Cart ');
3

4 async function addToCart (userId , productId , quantity ) {


5 try {
6 const cart = await Cart. findOneAndUpdate (
7 { user: userId },
8 {
9 $push : { items : { product : productId , quantity } },
10 $set: { updatedAt : new Date () }
11 },
12 { new: true , upsert : true }
13 );
14 return cart;
15 } catch ( error ) {
16 console .error (' Error adding to cart:', error );
17 throw error;
18 }
19 }

4.13 Question 28: Calculate Cart Total


Write a query to calculate the total price of a cart.
1 const mongoose = require ('mongoose ');
2 const Cart = require ( './ models /Cart ');
3

4 async function calculateCartTotal ( cartId ) {


5 try {
6 const result = await Cart. aggregate ([
7 { $match : { _id: mongoose . Types . ObjectId ( cartId ) } },

11
8 { $unwind : '$items ' },
9 { $lookup : { from: 'products ', localField : 'items .
product ', foreignField : '_id ', as: 'productData ' } },
10 { $unwind : '$productData ' },
11 { $group : {
12 _id: '$_id ',
13 total : { $sum: { $multiply : [' $items .quantity ', '
$productData .price '] } }
14 }}
15 ]);
16 return result [0]?. total || 0;
17 } catch ( error ) {
18 console .error (' Error calculating total :', error );
19 throw error;
20 }
21 }

4.14 Question 29: Remove Item from Cart


Write a query to remove an item from a cart.
1 const mongoose = require ('mongoose ');
2 const Cart = require ( './ models /Cart ');
3

4 async function removeFromCart (cartId , productId ) {


5 try {
6 const cart = await Cart. findByIdAndUpdate (
7 cartId ,
8 { $pull: { items : { product : productId } } },
9 { new: true }
10 );
11 return cart;
12 } catch ( error ) {
13 console .error (' Error removing from cart:', error );
14 throw error;
15 }
16 }

4.15 Question 30: Create Cart Index


Create an index for efficient cart queries.
1 db. carts . createIndex ({ user: 1 });

5 React
5.1 Question 31: Counter Component
Create a counter component using useState.

12
1 import React , { useState } from 'react ';
2

3 function Counter () {
4 const [count , setCount ] = useState (0);
5

6 return (
7 <div >
8 <p>Count : { count }</p>
9 <button onClick ={() => setCount ( count + 1)}>Increment </
button >
10 <button onClick ={() => setCount ( count - 1)}>Decrement </
button >
11 </div >
12 );
13 }
14

15 export default Counter ;

5.2 Question 32: Fetch and Display Data


Create a component to fetch and display data using useEffect.
1 import React , { useState , useEffect } from 'react ';
2

3 function DataFetcher () {
4 const [data , setData ] = useState ([]);
5 const [loading , setLoading ] = useState (true);
6

7 useEffect (() => {


8 fetch('https :// jsonplaceholder . typicode .com/posts ')
9 .then( response => response .json ())
10 .then(data => {
11 setData (data. slice (0, 5));
12 setLoading ( false );
13 })
14 . catch (error => {
15 console . error (' Error fetching data:', error );
16 setLoading ( false );
17 });
18 }, []);
19

20 return (
21 <div >
22 { loading ? <p> Loading ... </p> : (
23 <ul >
24 {[Link](post => (
25 <li key ={ [Link]}>{ post. title }</li >
26 ))}
27 </ul >
28 )}

13
29 </div >
30 );
31 }
32

33 export default DataFetcher ;

5.3 Question 33: Controlled Input Component


Create a controlled input component.
1 import React , { useState } from 'react ';
2

3 function TextInput () {
4 const [text , setText ] = useState ('');
5

6 return (
7 <div >
8 <input
9 type =" text"
10 value ={ text}
11 onChange ={(e) => setText (e. target . value )}
12 placeholder =" Type something ..."
13 />
14 <p>You typed : {text }</p>
15 </div >
16 );
17 }
18

19 export default TextInput ;

5.4 Question 34: Pass Props to Child Component


Create a parent component that passes props to a child.
1 import React from 'react ';
2

3 function Child ({ message }) {


4 return <p >{ message }</p >;
5 }
6

7 function Parent () {
8 return <Child message =" Hello from Parent !" />;
9 }
10

11 export default Parent ;

5.5 Question 35: Auto-Focus Input


Use useRef to focus an input on mount.

14
1 import React , { useRef , useEffect } from 'react ';
2

3 function AutoFocusInput () {
4 const inputRef = useRef (null);
5

6 useEffect (() => {


7 inputRef . current . focus ();
8 }, []);
9

10 return <input ref ={ inputRef } type =" text" placeholder =" Start
typing ..." />;
11 }
12

13 export default AutoFocusInput ;

5.6 Question 36: Toggle Button Component


Create a toggle button component.
1 import React , { useState } from 'react ';
2

3 function ToggleButton () {
4 const [isOn , setIsOn ] = useState ( false );
5

6 return (
7 <button onClick ={() => setIsOn (! isOn)}>
8 {isOn ? 'ON ' : 'OFF '}
9 </button >
10 );
11 }
12

13 export default ToggleButton ;

5.7 Question 37: Theme Switching with Context API


Create a component to switch themes using Context API.
1 import React , { createContext , useContext , useState } from 'react ';
2

3 const ThemeContext = createContext ();


4

5 function ThemeProvider ({ children }) {


6 const [theme , setTheme ] = useState ('light ');
7

8 return (
9 <ThemeContext . Provider value ={{ theme , toggleTheme : () =>
setTheme ( theme === 'light ' ? 'dark ' : 'light ') }}>
10 { children }
11 </ ThemeContext .Provider >
12 );

15
13 }
14

15 function ThemeComponent () {
16 const { theme , toggleTheme } = useContext ( ThemeContext );
17 return (
18 <div style ={{ background : theme === 'light ' ? '#fff ' :
'#333', color : theme === 'light ' ? '#000 ' : '#fff ' }}>
19 <p> Current theme : { theme }</p>
20 <button onClick ={ toggleTheme }> Toggle Theme </ button >
21 </div >
22 );
23 }
24

25 export default function App () {


26 return (
27 <ThemeProvider >
28 <ThemeComponent />
29 </ ThemeProvider >
30 );
31 }

5.8 Question 38: Form Submission


Create a form component with submission handling.
1 import React , { useState } from 'react ';
2

3 function Form () {
4 const [name , setName ] = useState ('');
5

6 const handleSubmit = (e) => {


7 e. preventDefault ();
8 alert(` Submitted : ${name }`);
9 };
10

11 return (
12 <form onSubmit ={ handleSubmit }>
13 <input
14 type =" text"
15 value ={ name}
16 onChange ={(e) => setName (e. target . value )}
17 placeholder =" Enter name"
18 />
19 <button type =" submit ">Submit </ button >
20 </form >
21 );
22 }
23

24 export default Form;

16
5.9 Question 39: Dynamic List Rendering
Create a component to render a dynamic list.
1 import React from 'react ';
2

3 function ItemList ({ items }) {


4 return (
5 <ul >
6 { items .map(item => (
7 <li key ={ [Link]}>{ [Link] }</li >
8 ))}
9 </ul >
10 );
11 }
12

13 export default function App () {


14 const items = [
15 { id: 1, name: 'Apple ' },
16 { id: 2, name: 'Banana ' },
17 { id: 3, name: 'Orange ' }
18 ];
19 return <ItemList items ={ items } />;
20 }

5.10 Question 40: Update Document Title


Use useEffect to update the document title.
1 import React , { useState , useEffect } from 'react ';
2

3 function TitleUpdater () {
4 const [count , setCount ] = useState (0);
5

6 useEffect (() => {


7 document .title = `Count : ${ count }`;
8 }, [ count ]);
9

10 return (
11 <div >
12 <p>Count: { count }</p>
13 <button onClick ={() => setCount ( count + 1)}>Increment </
button >
14 </div >
15 );
16 }
17

18 export default TitleUpdater ;

17
5.11 Question 41: Toggle Visibility
Create a component to toggle content visibility.
1 import React , { useState } from 'react ';
2

3 function ToggleContent () {
4 const [isVisible , setIsVisible ] = useState ( false );
5

6 return (
7 <div >
8 <button onClick ={() => setIsVisible (! isVisible )}>
9 { isVisible ? 'Hide ' : 'Show '} Content
10 </button >
11 { isVisible && <p>This is some content !</p >}
12 </div >
13 );
14 }
15

16 export default ToggleContent ;

5.12 Question 42: Deletable List


Create a component to display a list with delete buttons.
1 import React , { useState } from 'react ';
2

3 function DeletableList () {
4 const [items , setItems ] = useState (['Apple ', 'Banana ', 'Orange
']);
5

6 const deleteItem = ( index ) => {


7 setItems (items . filter ((_, i) => i !== index ));
8 };
9

10 return (
11 <ul >
12 { items .map (( item , index ) => (
13 <li key ={ index }>
14 {item}
15 <button onClick ={() => deleteItem ( index )}>Delete
</ button >
16 </li >
17 ))}
18 </ul >
19 );
20 }
21

22 export default DeletableList ;

18
5.13 Question 43: Timer Component
Create a timer component using useEffect.
1 import React , { useState , useEffect } from 'react ';
2

3 function Timer () {
4 const [seconds , setSeconds ] = useState (0);
5

6 useEffect (() => {


7 const interval = setInterval (() => {
8 setSeconds (prev => prev + 1);
9 }, 1000);
10 return () => clearInterval ( interval );
11 }, []);
12

13 return <p> Seconds : { seconds }</p >;


14 }
15

16 export default Timer ;

5.14 Question 44: Multiple Input Form


Create a component to handle multiple inputs.
1 import React , { useState } from 'react ';
2

3 function MultiInputForm () {
4 const [form , setForm ] = useState ({ name: '', email : '' });
5

6 const handleChange = (e) => {


7 setForm ({ ... form , [e. target .name ]: e. target . value });
8 };
9

10 const handleSubmit = (e) => {


11 e. preventDefault ();
12 alert(`Name: ${[Link]}, Email : ${form. email }`);
13 };
14

15 return (
16 <form onSubmit ={ handleSubmit }>
17 <input
18 type =" text"
19 name =" name"
20 value ={ [Link]}
21 onChange ={ handleChange }
22 placeholder =" Name"
23 />
24 <input
25 type =" email "
26 name =" email "
27 value ={ form. email }

19
28 onChange ={ handleChange }
29 placeholder =" Email "
30 />
31 <button type =" submit ">Submit </ button >
32 </form >
33 );
34 }
35

36 export default MultiInputForm ;

5.15 Question 45: Conditional Rendering


Create a component to conditionally render content.
1 import React , { useState } from 'react ';
2

3 function ConditionalRender () {
4 const [isLoggedIn , setIsLoggedIn ] = useState ( false );
5

6 return (
7 <div >
8 <button onClick ={() => setIsLoggedIn (! isLoggedIn )}>
9 { isLoggedIn ? 'Log Out ' : 'Log In '}
10 </button >
11 { isLoggedIn ? <p>Welcome , User !</p> : <p> Please log in
.</p>}
12 </div >
13 );
14 }
15

16 export default ConditionalRender ;

6 Problem-Solving
6.1 Question 46: Second Largest Number
Write a function to find the second largest number in an array.
1 function secondLargest (arr) {
2 if (arr. length < 2) return null;
3 const sorted = [... new Set(arr)]. sort ((a, b) => b - a);
4 return sorted [1] || null;
5 }
6 console .log( secondLargest ([3 , 1, 4, 1, 5, 9, 2])); // Output : 5

6.2 Question 47: Balanced Parentheses


Write a function to check if a string has balanced parentheses.

20
1 function isBalanced (str) {
2 const stack = [];
3 for (let char of str) {
4 if (char === '(') stack .push(char);
5 else if (char === ') ') {
6 if (! stack .pop ()) return false ;
7 }
8 }
9 return stack. length === 0;
10 }
11 console .log( isBalanced ("((() ))")); // Output : true

6.3 Question 48: Fibonacci Sequence


Write a function to generate Fibonacci numbers up to n.
1 function fibonacci (n) {
2 if (n < 0) return [];
3 const fib = [0, 1];
4 for (let i = 2; i <= n; i++) {
5 fib[i] = fib[i - 1] + fib[i - 2];
6 }
7 return fib. slice (0, n + 1);
8 }
9 console .log( fibonacci (5)); // Output : [0, 1, 1, 2, 3, 5]

6.4 Question 49: Create Product Route


Write an Express route to create a product.
1 const express = require ('express ');
2 const router = express . Router ();
3 const Product = require ( './ models /Product ');
4

5 router .post ('/ products ', async (req , res) => {


6 try {
7 const { name , price , stock , category } = [Link];
8 const product = new Product ({ name , price , stock , category
});
9 await product .save ();
10 res. status (201) .json( product );
11 } catch ( error ) {
12 res. status (500) .json ({ message : 'Error creating product ',
error });
13 }
14 });
15

16 module . exports = router ;

21
6.5 Question 50: Reverse Words in a Sentence
Write a function to reverse words in a sentence.
1 function reverseWords ( sentence ) {
2 return sentence . split (' ').map(word => word. split (''). reverse ().
join ('')).join(' ');
3 }
4 console .log( reverseWords (" Hello World ")); // Output : " olleH dlroW "

6.6 Question 51: First Non-Repeating Character


Write a function to find the first non-repeating character in a string.
1 function firstNonRepeating (str) {
2 const charCount = {};
3 for (let char of str) {
4 charCount [char] = ( charCount [char] || 0) + 1;
5 }
6 for (let char of str) {
7 if ( charCount [char] === 1) return char;
8 }
9 return null;
10 }
11 console .log( firstNonRepeating (" swiss ")); // Output : "w"

6.7 Question 52: Filter List Component


Create a React component to filter a list.
1 import React , { useState } from 'react ';
2

3 function FilterList ({ items }) {


4 const [filter , setFilter ] = useState ('');
5

6 const filteredItems = items . filter (item =>


7 [Link]. toLowerCase (). includes ( filter . toLowerCase ())
8 );
9

10 return (
11 <div >
12 <input
13 type =" text"
14 value ={ filter }
15 onChange ={(e) => setFilter (e. target . value )}
16 placeholder =" Filter items ..."
17 />
18 <ul >
19 { filteredItems .map(item => (
20 <li key ={ [Link]}>{ [Link] }</li >
21 ))}
22 </ul >

22
23 </div >
24 );
25 }
26

27 export default function App () {


28 const items = [
29 { id: 1, name: 'Apple ' },
30 { id: 2, name: 'Banana ' },
31 { id: 3, name: 'Orange ' }
32 ];
33 return <FilterList items ={ items } />;
34 }

6.8 Question 53: Merge Sorted Arrays


Write a function to merge two sorted arrays.
1 function mergeSortedArrays (arr1 , arr2) {
2 const merged = [];
3 let i = 0, j = 0;
4 while (i < arr1. length && j < arr2. length ) {
5 if (arr1[i] <= arr2[j]) {
6 merged .push(arr1[i++]);
7 } else {
8 merged .push(arr2[j++]);
9 }
10 }
11 return merged . concat (arr1. slice (i), arr2. slice (j));
12 }
13 console .log( mergeSortedArrays ([1 , 3, 5], [2, 4, 6])); // Output : [1,
2, 3, 4, 5, 6]

6.9 Question 54: Request Logger Middleware


Write an Express middleware for logging requests.
1 function loggerMiddleware (req , res , next) {
2 console .log(`${req. method } ${[Link]} - ${new Date (). toISOString
()}`);
3 next ();
4 }
5

6 module . exports = loggerMiddleware ;

6.10 Question 55: Power of Two


Write a function to check if a number is a power of two.
1 function isPowerOfTwo (n) {
2 if (n <= 0) return false ;

23
3 return (n & (n - 1)) === 0;
4 }
5 console .log( isPowerOfTwo (16)); // Output : true
6 console .log( isPowerOfTwo (18)); // Output : false

6.11 Question 56: Rotate Array


Write a function to rotate an array by k positions.
1 function rotateArray (arr , k) {
2 if (! arr. length ) return arr;
3 k = k % arr. length ;
4 return [... [Link] (-k), ... arr. slice (0, -k)];
5 }
6 console .log( rotateArray ([1 , 2, 3, 4, 5], 2)); // Output : [4, 5, 1,
2, 3]

6.12 Question 57: Longest Common Prefix


Write a function to find the longest common prefix in an array of strings.
1 function longestCommonPrefix (strs) {
2 if (! strs. length ) return "";
3 let prefix = strs [0];
4 for (let str of strs) {
5 while (str. indexOf ( prefix ) !== 0) {
6 prefix = prefix . slice (0, -1);
7 if (! prefix ) return "";
8 }
9 }
10 return prefix ;
11 }
12 console .log( longestCommonPrefix ([" flower ", "flow", " flight "])); //
Output : "fl"

6.13 Question 58: Valid Email


Write a function to check if a string is a valid email.
1 function isValidEmail ( email ) {
2 const regex = /^[^\ s@ ]+@[^\ s@ ]+\.[^\ s@ ]+$/;
3 return [Link]( email );
4 }
5 console .log( isValidEmail (" user@example .com ")); // Output : true
6 console .log( isValidEmail (" invalid . email@ ")); // Output : false

6.14 Question 59: Products by Price Range


Write an Express route to get products by price range.

24
1 const express = require ('express ');
2 const router = express . Router ();
3 const Product = require ( './ models /Product ');
4

5 router .get ('/ products /price ', async (req , res) => {
6 try {
7 const { min , max } = req. query ;
8 const products = await Product .find ({
9 price: { $gte: Number (min), $lte: Number (max) }
10 });
11 [Link]( products );
12 } catch ( error ) {
13 res. status (500) .json ({ message : 'Error fetching products ',
error });
14 }
15 });
16

17 module . exports = router ;

6.15 Question 60: Two Sum


Write a function to find indices of two numbers that sum to a target.
1 function twoSum (nums , target ) {
2 const map = {};
3 for (let i = 0; i < nums. length ; i++) {
4 const complement = target - nums[i];
5 if (map[ complement ] !== undefined ) {
6 return [map[ complement ], i];
7 }
8 map[nums[i]] = i;
9 }
10 return [];
11 }
12 console .log( twoSum ([2 , 7, 11, 15] , 9)); // Output : [0, 1]

25

You might also like