0% found this document useful (0 votes)
3K views

Frontend Interview

Frontend interview questions 2024

Uploaded by

taigrus
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)
3K views

Frontend Interview

Frontend interview questions 2024

Uploaded by

taigrus
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
You are on page 1/ 164

Front End

Interview Ebook
Perfect for MAANG, MNCs & Startups Alike! Tailored for
MAANG & MNC | Over 150 Insights from Top MNC
Interviewers.
Ujjal Ray | FE-I Cognizant | Linkdin: https://www.linkedin.com/in/ujjal-ray-41776b254/

more interview free on : https://learndepth.com/


Key Interview Tip: Combine Theory with Practice

Always provide both a theoretical explanation and a practical example


during your interview. Share your screen to demonstrate your approach
in real-time. This not only showcases your practical skills but also gives
you more control over the pace of the interview, reinforcing your image
as a hands-on problem solver.

This PDF Includes:

● 100+ JavaScript Theory Interview Questions: Deep dive into core


concepts and best practices.
● 50+ Output-Based JavaScript Questions: Test your understanding
with practical scenarios.
● 60+ React.js Theory and Practical Questions: Comprehensive
coverage of React.js concepts and real-world applications.

1
What is the Event Loop in JavaScript? 🌟🌟🌟
(Most asked in all the interviews 99% chance)

The event loop is a core concept in JavaScript's concurrency model,


enabling the execution of asynchronous code despite JavaScript's
single-threaded nature. It ensures that non-blocking tasks, like I/O
operations and timers, are handled efficiently.

Call Stack:

● The call stack is where JavaScript keeps track of function calls.


When a function is invoked, it's added to the stack, and when it's
finished, it's removed.

2
Callback Queue (Task Queue):
● This queue holds callbacks and messages that are waiting to be
executed. When an asynchronous operation like a setTimeout or
network request is completed, its callback is placed in this queue.

Event Loop:
● The event loop constantly checks the call stack and the callback
queue.
● If the call stack is empty, the event loop moves the first callback from
the callback queue to the call stack, allowing it to execute.

3
Different Ways to Create an Object in JavaScript 🌟🌟🌟
(Most Asked)

1. Object Literal 👍:

Explanation:

The object literal is the simplest and most common way to create an object
in JavaScript. You define the object using curly braces {}, and specify
properties inside the braces as key-value pairs.

2. Using the new Object() Constructor 👍

The new Object() syntax is less commonly used but is another way to
create an object. It creates an empty object and properties are then added
to it.

4
3.Using ES6 Classes:

Explanation:

ES6 introduced classes as a more intuitive way to create objects and handle
inheritance. Classes are essentially syntactic sugar over the prototype-based
inheritance model in JavaScript.

4 .Using Object.assign():

Explanation:

Object.assign() is used to copy properties from one or more


source objects to a target object. It’s a quick way to create a
new object by combining existing objects.

5
What is Event Bubbling? 🌟🌟🌟 (Most Asked)

Event Bubbling is a process in JavaScript where an event starts at the


element where it occurred and then moves up to its parent elements in
the DOM.

6
What is Event Capturing?
Event Bubbling is a process in JavaScript where an event starts at the
element where it occurred and then moves up to its parent elements in
to Child elements in the DOM.
You can enable event capturing by passing true as the third argument to addEventListener
.

7
What are the differences between call(), apply() and bind()?

🌟🌟🌟
😉Interview Tip:
Execute and Explain: During the interview, after explaining the differences, run
these examples in a JavaScript console. Walk the interviewer through each
example, showing how this context is set and how arguments are passed
differently. This approach demonstrates your practical understanding and helps
clarify the concepts.

The primary use of call(), apply(), and bind() is to change the


context of this keyword within a function. this keyword refers to the object
that the function is called on.

call(): Invoke a function with a specific this and arguments pass one
by one .
apply(): Invoke a function with a specific this and arguments as an
array.
bind(): Create a new function with a specific this, to be called later,
optionally presetting some arguments.

call(): will invokes the function immediately with the given


this value and allow us to pass the arguments one by one 👈
with comma separator.

obj1.fun.call(obj2, "Hello", “world” ); 👈

8
obj1.fun.call(obj2): This line calls the fun method of obj1, but sets
this to obj2.

call(): will invokes the function immediately with the given

9
apply(): will invoke the function immediately with the given
this value and allow us to pass the arguments as an array. 👈
obj1.fun.apply(obj2, [10,20,30,40,50] ); 👈

10
The bind() method is a bit different from call() and apply(). It doesn't
invoke the function immediately. Instead, it creates a new function with a
specified context and any provided arguments. You can then invoke this
new function at a later time.

Using bind to create a new function with obj2 as the this context and
passing a greeting and an array of numbers .

11
What are the various things hoisted in javascript ?

👉 Interview Tip: Mention buzz word temporal dead zone in above answer so that
interviewer will ask What is temporal dead zone. 🤪

What is the temporal dead zone ?


It is a specific time period in the execution of javascript code where the variables
declared with let and const exist but cannot be accessed until the value is assigned.
Any attempt to access them result in reference errors

12
🌟🌟🌟
What are the limitations of arrow functions in javascript ?
(Most Asked)

1. Arrow functions cannot be accessed before initialization

2. Arrow function does not have access to arguments object

3. Arrow function does not have this. Instead, they inherit this from the
surrounding code at the time the function is defined.

4. Arrow functions cannot be used as constructors. Using them with the 𝙣𝙚𝙬
keyword to create instances throws a TypeError.

5. Arrow functions cannot be used as generator functions.

What's the difference between Object.keys,values and entries ?

13
What's the difference between Object.freeze() vs Object.seal() ?

14
15
What is a polyfill in javascript ? 🌟🌟🌟
👉 Interview Tip: If polyfill is asked, then 99% they will ask you to write a polyfill. So
practice at least 2-3 polyfills (map,foreach compulsory)

16
17
What is a prototype in javascript ? 🌟🌟🌟
👉 Interview Tip: 99% they will ask you ager ai question nai pucha to mara name badal
dena 😉

Prototypal inheritance is a feature in JavaScript that allows objects to inherit


properties and methods from other objects. This is different from classical
inheritance found in languages like Java or C++, where classes inherit from
other classes.

18
What is Callback Hell in JavaScript ? 🌟🌟🌟
Callback hell in JavaScript refers to a situation where multiple nested callback
functions make the code difficult to read, debug, and maintain. This often results in
a “pyramid” or “mushroom” shape, where each callback is nested inside another,
leading to deeply indented and hard-to-follow code.

Write Comments: Adding comments can help explain the purpose of each callback and
make the code more readable.

Split Functions: Break down large functions into smaller, more manageable ones.

Use Promises: Promises can help flatten the structure of nested callbacks.

Async/Await: This modern syntax makes asynchronous code look more like synchronous
code, improving readability.

19
Above example using Promises:

Above example using async/await:

20
Promise in JavaScript ? 🌟🌟🌟
A Promise in JavaScript Promise is used to handle asynchronous operations. It
allows us to work with code that will complete in the future (like data fetching, file reading,
etc.) without blocking the rest of the code. Promises improve readability and maintainability
by helping us handle complex workflows that involve waiting for actions to complete

21
1. States of a Promise:

● Pending: The initial state of a promise. The promise is neither fulfilled


nor rejected.
● Fulfilled: The state of a promise when the asynchronous operation is
completed successfully.
● Rejected: The state of a promise when the asynchronous operation
fails.

2.Promise Object:

● The Promise object has methods to handle asynchronous results:


then(), catch(), and finally().

Handling Multiple Promises:

22
Summary

● Promise represents the result of an asynchronous operation and can be


in one of three states: pending, fulfilled, or rejected.
● You create a promise using the Promise constructor and handle its
result with then(), catch(), and finally().

23
30. What is authentication vs authorization ? (Most asked)

What are the difference between typescript and javascript ?

24
What are callbacks Function in javascript ?
A callback is a function which is passed as an argument to another function which
can be executed later in the code.

Use Cases:

● setTimeOut Higher order functions ( Like map,filter,forEach ).


● Handling events ( Like click/key press events ).
● Handling asynchronous operations ( Like reading files, making Http requests).

What is Eval in JavaScript ?

25
What are Higher Order Functions in javascript ?

26
What are the various array methods in javascript ?
Basic Methods:

● push(): Adds one or more elements to the end of an array and returns the new
length.
● pop(): Removes the last element from an array and returns that element.
● shift(): Removes the first element from an array and returns that element.
● unshift(): Adds one or more elements to the beginning of an array and returns the
new length.
● concat(): Merges two or more arrays and returns a new array.
● slice(): Returns a shallow copy of a portion of an array into a new array object.
● splice(): Adds or removes elements from an array.
● copyWithin(): method shallow copies part of an array to another location in the
same array and returns it without modifying its length.
● The flat(): method creates a new array with all sub-array elements concatenated
into it recursively up to the specified depth.

27
What are the differences between some and every in javascript ?

28
What are the different types of errors in javascript ?

29
30
What is tree shaking in javascript ?

Tree shaking relies on the static structure of ES6 (ECMAScript 2015) module
syntax, specifically the import and export statements. By analyzing these
statements, tree shaking tools can determine which parts of the code are actually
used and which can be safely removed.

31
32
What is Babel ?

Babel is a javascript compiler which is used to convert the modern javascript


code into the version that is understandable by all the modern and older
browsers.

What are the main advantages of arrow functions ?

33
34
Difference Between null and undefined 🌟🌟🌟
null:

● Meaning: null is an assignment value. It means that a variable is explicitly


set to have "no value."
● Usage: Used to indicate the intentional absence of any object value.

undefined:

● Meaning: undefined means that a variable has been declared but has not
yet been assigned a value.
● Usage: Represents the absence of a value or the absence of an initialized
value in a variable.

35
Difference Between == and === in JavaScript 🌟🌟🌟
== will check for equality of values

where === will check for equality as well as data types.

36
What is a Closure? 🌟🌟🌟
(Most asked in all the interviews 99% chance)
Definition: A closure is a feature in JavaScript where an inner function has
access to the outer (enclosing) function’s variables, even after the outer
function has returned. Closures allow functions to retain access to variables
from their enclosing scope.

37
1 . What are the different data types in javascript ? (Most asked)

Answer: JavaScript has two main categories of data types:

Primitive Data Types:

1. String: Represents a sequence of characters. Example: "Hello World"


2. Number: Represents numerical values, both integers and floating-point
numbers. Example: 42, 3.14
3. Boolean: Represents a logical value, either true or false. Example: true,
false
4. null: Represents the intentional absence of any object value. Example:
null
5. undefined: Represents a variable that has been declared but has not yet
been assigned a value. Example: undefined
6. BigInt: Represents integers with arbitrary precision. Example:
1234567890123456789012345678901234567890n
7. Symbol: Represents a unique and immutable value often used as object
property keys. Example: Symbol('description')

Non-Primitive (Reference) Data Types:

1. Object: Represents a collection of key-value pairs. Example: { name:


"Alice", age: 25 }
2. Array: A special type of object used for storing ordered collections.
Example: [1, 2, 3, 4]
3. Date: Represents dates and times. Example: new Date('2024-08-19')

38
3. Hoisting in JavaScript ? 🌟🌟🌟
Hoisting in JavaScript means that when you declare variables or
functions, JavaScript moves their declarations to the top of the scope
before the code actually runs. However, only the declarations are
hoisted, not the initializations.

How Hoisting Works:

● Variable Declarations: The declarations are hoisted to the top, but


their initializations are not. This means that if you try to use a
variable before its declaration, it will result in undefined if
declared with var, and it will cause a ReferenceError if declared
with let or const.
● Function Declarations: Entire function declarations (both the
name and the body) are hoisted. This allows functions to be called
before they are defined in the code.

39
4. What is the temporal dead zone ?
It is a specific time period in the execution of javascript code where the
variables declared with let and const exists but cannot be accessed
until the value is assigned. Any attempt to access them result in
reference errors.

🌟🌟🌟
6. What are the differences between let, var and const ?
(Most asked)
Scope:

● var: Function-scoped or globally scoped.


● let: Block-scoped.
● const: Block-scoped.

Hoisting:

● var: Hoisted and initialized with undefined.


● let: Hoisted but not initialized; accessing before declaration results in a
ReferenceError.
● const: Hoisted but not initialized; accessing before declaration results in a
ReferenceError.

Reassignment:

● var: Can be reassigned and redeclared within the same scope.


● let: Can be reassigned but not redeclared in the same scope.
● const: Cannot be reassigned or redeclared; must be initialized at declara

40
7. List out some key features of ES6 ? (Most asked)

● Arrow functions
● Let and Const declarations.
● Destructuring assignment
● Default parameters
● Template literals
● Spread and Rest operators
● Promises
● Classes
● Modules
● Map, Set, Weakmap, Weakset

41
4. Default Parameters in JavaScript ?
Default parameters in JavaScript allow you to set default values for
function parameters if no value or undefined is provided when the
function is called. This feature was introduced in ECMAScript 2015 (ES6).

Passing functions as default parameters can be particularly useful for


setting up customizable behaviours in your code.

42
5. Template Literals in JavaScript ? 🌟🌟🌟
Template literals in JavaScript, introduced with ECMAScript 2015 (ES6),
provide a way that you can concat variable with strings .

Template literals use backticks (`) instead of single quotes (') or double
quotes (").

43
5. Find and FindIndex in JavaScript ?

The find method returns the first element in the array that
satisfies and The findIndex method returns the index of the first
element in the array that satisfies , If no elements satisfy the
condition, it returns -1.

44
6. Arrow Function in JavaScript ? 🌟🌟🌟
Arrow functions in JavaScript, introduced with ECMAScript 2015 (ES6),
provide a shorter syntax for writing functions. They also differ from
traditional function expressions in terms of how they handle the this
keyword.

45
Summary:

● Arrow functions provide a concise syntax for writing


functions.
● They do not have their own this context and inherit this
from their lexical scope.
● They cannot be used as constructors and do not have an
arguments object.
● They are particularly useful for writing shorter functions and
handling this more intuitively in callbacks.

1. Shorter Syntax:

● For a single expression, then no need to return a statement .


● If there is only one parameter,then no need to parentheses

46
2.this Binding:

● Arrow functions do not have their own this context.


● This is particularly useful in cases where traditional functions
create issues with this in callbacks.

47
5 . Rest Operator in JavaScript ? 🌟🌟🌟
The rest operator in JavaScript is a syntax introduced with ECMAScript
2018 (ES8) that allows you to represent an indefinite number of
arguments as an array. It is used to collect all remaining elements into a
single array parameter in function arguments, destructuring
assignments, and more.

The rest operator is denoted by three consecutive dots (...) followed by


the name of the parameter or variable.

1.Function Parameters:

The rest operator can be used in function parameters to collect multiple


arguments into an array.

In this example, the ...numbers parameter collects all the arguments passed
to the sum function into the numbers array.

48
2. Destructuring Arrays: 🌟🌟🌟
● The rest operator can be used to collect the remaining elements of an
array into a new array during destructuring.
● It is allows you to unpack values from arrays or properties from objects
into distinct variables.

3. Destructuring Objects: 🌟🌟🌟


● The rest operator can be used to collect the remaining properties of an
object into a new object during destructuring.

49
6 . Spread Operator in JavaScript ? 🌟🌟🌟
It allows you to expand or spread elements from an iterable (such as an
array or object) into individual elements or properties. It is denoted by
three consecutive dots (...) followed by the iterable.

In this example, ...fruits spreads the elements of the fruits array into the
moreFruits array.

In this example, updatedPerson is a new object with the properties from


person and additional or updated properties.

Shallow Copy: The spread operator creates a shallow copy of an array or


object. This means that if the array or object contains nested objects or arrays,
those nested structures are not deeply copied but referenced.

50
8 . Async and await in JavaScript ? 🌟🌟🌟
async and await are modern JavaScript features introduced in
ECMAScript 2017 (ES8) that simplify working with asynchronous code.
They provide a cleaner syntax for handling asynchronous operations
compared to using callbacks or promises directly.

51
9 . Global Function in JavaScript ?

Global functions are functions that are available globally, meaning they
can be accessed and invoked from anywhere in your code.

isFinite()

● Determines whether a value is a finite number. Returns true if the


value is a finite number, and false otherwise.

isNaN()

● Determines whether a value is NaN (Not-a-Number). Returns true if the


value is NaN, and false otherwise.

52
10 . Generators in JavaScript ? 🌟🌟🌟
Generators in JavaScript are special functions that can be paused and
resumed, allowing them to yield multiple values over time. They provide
a way to work with sequences of values and manage asynchronous
operations more easily. Generators were introduced in ECMAScript 2015
(ES6).

53
11 . Deep Copy and Shallow Copy JavaScript ?

🌟🌟🌟
when we copy one object to another object in this case object data is
not copied object reference is copied in this case we can used :

Shallow Copy :

A shallow copy creates a new object, but only copies the top-level
properties from the original object. Its work only single level .

54
Deep Copy :

A deep copy creates a new object and recursively copies all properties and
nested objects from the original object.

Here we have a problem that function is remove here :

55
12. What are the differences between Map and Set ?

56
13. What are modules in javascript ?
● Modules allow us to break down the large piece of code into smaller
parts.
● Modules help us to write more reusable and maintainable code.
● Modules can be imported and exported using import and export
statements.

14. What is the difference between 'Pass by Value' and


'Pass by Reference'?
In JavaScript, whenever a function is called, the arguments can be passed in two
ways, either pass by value or pass by reference.

● Primitive datatypes such as string, number,boolean,null and undefined are


passed by value.
● Non -primitive datatypes such as object,arrays or functions are passed by
reference.

In Pass by value, parameters passed as an arguments creates their own copy.


So any changes made inside the function are made to the copied value so it will
not affect the original value.

57
58
15. Difference Between map and filter? (Frequently asked)

Purpose:🌟🌟🌟
● map: Transforms each element of an array and returns a new array with the
transformed elements.
● filter: Creates a new array with only those elements that satisfy a
specified condition.

Return Value:

● map: Returns a new array with transformed elements.


● filter: Returns a new array with elements that pass the test implemented
by the provided function.

59
16. Difference Between map() and forEach()?

🌟🌟🌟
Purpose:

● map(): Used to transform the elements of an array.


● forEach(): Used to loop through the elements of an array.

Return Value:

● map(): Returns a new array with transformed values.


● forEach(): Does not return a new array; returns undefined.

Usage with Other Methods:

● map(): Can be chained with other array methods like filter.


● forEach(): Cannot be chained with other array methods
because it does not return a new array.

60
17. Difference Between for-in and for-of
🌟🌟🌟
● for-in: Iterates over the enumerable property keys of an
object.
● for-of: Iterates over the values of an iterable object
(e.g., arrays, strings).

61
What is the difference between Pure and Impure functions?

Pure functions are the functions which will return the same output for the
same arguments passed to the function.

● This will not have any side effects.


● It does not modify any non-local state.

Impure functions are functions that can produce different outputs even when
given the same input, because they rely on or modify external factors (non-local
state). They also have side effects, meaning they can change something outside
their own scope.

62
Guess the output ?

63
64
False,False

In JavaScript, when you compare objects using == or === , you're comparing their
references in memory, not their actual contents. Even if two objects have the same
properties and values, they are considered unequal unless they reference the exact
same object in memory.

Output of below logic ?

65
66
Guess the output ?

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Problem solving questions

Access more interview questions including these for free on


https://learndepth.com/

1. Write a program to remove duplicates from an array ?

89
2. How to check whether a string is palindrome or not ?

3. Find the factorial of a given number ?

90
4. Write a JavaScript function to check if a given number is prime.

5. Program to find Reverse of a string without using built-in method

91
6. Find the max count of consecutive 1’ s in an array ?

92
7. Given 2 arrays that are sorted [0,3,4,31] and [4,6,30]. Merge them
and sort [0,3,4,4,6,30,31] ?

93
8.Write a JavaScript function that takes an array of numbers
and returns a new array with only the even numbers.

94
9. Program to find the longest word in a given sentence ?

10.Write JavaScript program to find the maximum number in an


array?

95
11. Find the smallest word in a given sentence ?

96
97
98
99
100
101
102
103
What is IIFE ?

What is CORS ? (Most asked)

104
Difference between undeclared and undefined variables?
Undeclared:

These variables does not exist in the program and they are not declared. If
we try to read the value of undeclared variable then we will get a runtime
error.

Undefined:

These variables are declared in the program but are not assigned any value.
If we try to access the value of undefined variables, It will return undefined.

What is the main difference between Local Storage and Session


storage ? (Most asked)
Local storage and session storage are two ways of storing data using
key value pairs in web browsers.
LocalStorage is the same as SessionStorage but it persists the data
even when the browser is closed and reopened and on reload(i.e it has
no expiration time) whereas in sessionStorage data gets cleared when
the page session ends.

105
106
What are cookies ?
Cookies are used to store information about the user in the webpages.
Cookies are stored as key value pairs and hold 4kb of data.
When a user logins to the application, the server uses the set-cookie
http header in the response to set a cookie with a unique session
identifier. Next time when the user makes the api requests, a cookie
will be sent in the http header by using which server will identify who
the user is.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013
12:00:00 UTC; path=/";

107
Reactjs Interview questions & Answers

1)What is ReactJs
React.js is a popular JavaScript library developed by Facebook for building fast and
interactive user interfaces, and single-page applications. It allows developers to create
reusable UI components and efficiently manage the DOM using a virtual DOM.

108
2)What are the features of React ?
JSX (JavaScript XML): React internally uses JSX that allows us to write html and
javaScript code together .

Virtual DOM: Whenever any underlying data changes or whenever a user enters
something in a textbox then the entire UI is rerendered in a virtual dom representation.

Now this virtual dom is compared with the original dom and creates a changeset which
will be applied on the real dom.

So instead of updating the entire realdom, it will be updated with only the things that
have actually been changed.

Hooks: React introduced Hooks in version 16.8, allowing developers to use state and
other React features in functional components. Common hooks include useState,
useEffect, and useContext.

Community and Support: React has a large and active community, with a wealth of
resources, tutorials, and third-party libraries available to help developers.

3)What is the Virtual DOM ?


Virtual DOM: React uses a Virtual DOM to efficiently update and render
components. When the state of a component changes, React updates the Virtual
DOM first and then syncs it with the actual DOM, minimizing the number of direct
manipulations to the DOM and improving performance.

:How the Virtual DOM Works:

109
1.Initial Rendering:

When a React component is first rendered, React creates a lightweight, in-memory


representation of the Real DOM, called the Virtual DOM. This Virtual DOM is a
JavaScript object that mirrors the structure of the actual DOM elements.

2.State and Props Changes:

When a component's state or props change, React updates the Virtual DOM. This
update does not immediately trigger changes to the Real DOM, which can be costly in
terms of performance.

3.Reconciliation:

React compares the updated Virtual DOM with the previous version to determine what
has changed. This process is called "reconciliation." React identifies the minimal set of
changes (diff) needed to update the Real DOM.

110
4.Updating the Real DOM:

Once the differences are identified, React efficiently updates only the parts of the Real
DOM that have changed. This selective update process is much faster than
re-rendering the entire DOM, leading to improved performance.

4) Explain the steps to create a react application and print


hello world?

Step 1: Install Node.js and npm

● Before you start, ensure that Node.js and npm (Node Package Manager) are
installed on your machine. You can download them from the official Node.js
website.

Step 2: Create a New React Application

● Once create-react-app is installed, you can create a new React application by


running the following command in your terminal:
● npx create-react-app my-first-react-app

Step 3: Navigate to the Project Directory

● Move into the newly created project directory:


● cd my-first-react-app

Step 5: Start the Development Server

● To see your React application in action, start the development server by running:
● npm start

111
Step 6: Modify the Default App Component to Print "Hello, World!"

Now, let's modify the code to print "Hello, World!" on the screen.

● Open the src directory in your project.


● Open the App.js file in your preferred code editor.

Replace the contents of App.js with the following code:

Summary:

1. Install Node.js and npm.


2. Install create-react-app.
3. Create a new React application.
4. Navigate to the project directory.
5. Start the development server.
6. Modify App.js to print "Hello, World!".
7. Save and view the result.

112
5) Explain the Basic Folder Structure in react application?

113
public/:

● index.html: The main HTML file that gets served by the development server. It
includes a <div> with the id="root" where your React app will be injected.
● favicon.ico: The icon displayed in the browser tab.
● manifest.json: Metadata for Progressive Web Apps (PWA), like the app’s name,
icons, and theme.

src/:

This is the heart of the React application where most of the development happens.

● index.js: The entry point of the application. It renders the root component
(usually <App />) into the DOM.
● App.js: The root component that typically contains the main layout and routing
logic.
● App.css: The global CSS file for styling the App.js component.

node_modules/

● Contains all the npm packages and dependencies for the project.

package.json

● It contains your Application Details metadata like the project name and version,
dependencies.

package.Lock.json

● It contains dependencies information like his version,license, link , etc.

114
6) Explain the Components in React And Types ?
Components are the building blocks or code of code of a React application that
help in organizing the application by dividing the UI into smaller, manageable
pieces.

Types of Components

There are two main types of components in React:

1. Functional Components
2. Class Components

115
116
The key differences between Functional Components and Class Components in React:

117
7) Explain the Class Component in React ?

Definition: Class components are ES6 classes that extend React.Component. They
can hold and manage their own state and have access to lifecycle methods.

118
State Management:

● Initialization: State is initialized in the constructor.


● Access: State is accessed via this.state.
● Update: State is updated using this.setState().

119
Lifecycle Methods:

In React Lifecycle describe the state of your component when your component is
created, updated and deleted.

Constructor:

● It’s called before the component is created. It’s used to initialize the component’s
state and bind event handlers to the component’s context.

● constructor();

120
Mounting:

Methods called when the component is being added to the DOM.

● componentDidMount()

Updating:

Methods called when the component updates.

● componentDidUpdate()

Unmounting:

Methods called when the component is being removed from the DOM.

● componentWillUnmount()

super() Function:

The super() function is used to call the constructor of the parent class
(React.Component in the case of React class components). This allows the component
to inherit methods and properties from React.Component and correctly initialize
this.props.

render() Function:

In function components, the render() method is not needed because the component
itself returns the JSX directly.

But in the class component The render() method returns JSX, which describes the
structure and content of the component’s UI.

121
8) Explain the Function Component in React ?

Functional components are JavaScript functions that return JSX. They are often
used for rendering UI and handling simple logic.

122
9) Explain the React Hooks ?

React Hooks are functions that allow you to use state and other React features in
function components. They were introduced in React 16.8 to enable state
management and lifecycle capabilities in function components, which previously
were only available in class components.

Key React Hooks

1)useState:

○ Purpose: Manages state in function components.

123
2)useEffect

● Purpose: Handles side effects like data fetching, subscriptions, or manually


changing the DOM, state changes .

124
3) useMemo

● Purpose: Memorizes expensive calculations to optimize performance.we can huddle


unwanted call
● Usage: Returns a memoized value, recalculating only when dependencies change.

125
4)useRef

Purpose:

● Access DOM Elements: Allows you to directly interact with a DOM element.
● Persist Mutable Values: Keeps a value across renders without causing a
re-render when updated.

126
5)contextApi

Purpose:

● React.createContext(): This function creates a Context object that includes a


Provider and a Consumer.
● Provider: Supplies the context value to its child components
● The useContext hook provides a simpler and more direct way to access context
values in function components.

127
128
6)Lazy Loading

Purpose:

● In React, lazy loading is used to load components only when they are required. Some
component complexity is very large in this case using Lazy Loading we load components
after .it helps to improve application performance.

129
7) suspense in React

Purpose:

● The lazy loaded components are wrapped by Suspense.The Suspense component


receives a fallback prop which is displayed until the lazy loaded component is rendered. .

130
10) Explain the Controlled Component in React ?
In React, a controlled component is a component whose form data (e.g., input values) is
handled by the React component's state rather than the DOM. This means that the form
data is controlled by React, making it easier to manage and validate the data.

131
11) Explain the UnControlled Component in React ?
React, an uncontrolled component, is a component where form data is handled
by the DOM using Ref .

132
133
12)Explain the Higher-Order Component in React ?
It is a function that takes a component and returns a new component with
enhanced or extended functionality. HOCs allow you to share common behavior
and logic across multiple components without repeating code.

134
135
13) Conditional Rendering in React?
In React, conditional rendering allows you to render different elements or
components based on certain conditions.

136
14) What are Fragments in React?
In React, fragments are used to group multiple elements without adding extra
nodes to the DOM. They are particularly useful when you want to return multiple
elements from a component without introducing unnecessary parent elements.

137
○ React.createElement is a method used to create React elements, while JSX
is a syntax extension that allows you to write HTML-like code within
JavaScript. JSX is compiled to React.createElement calls.

138
15) What is the difference between React.createElement and
JSX?
React.createElement is a method used to create React elements, while JSX is a syntax
extension that allows you to write HTML-like code within JavaScript. JSX is compiled to
React.createElement calls.

16) What is the difference between React.createElement and


JSX?
React.createElement is a method used to create React elements, while JSX is a syntax
extension that allows you to write HTML-like code within JavaScript. JSX is compiled to
React.createElement calls.

17) How do you Handle side effects in React?


Side effects in React can be handled using hooks like useEffect for functional
components or lifecycle methods like componentDidMount, componentDidUpdate, and
componentWillUnmount for class components.

139
18) What is the significance of keys in React?
Keys are used to uniquely identify the elements in the list.

react will use this to identify, which elements in the list have been added, removed or
updated

which items have changed, are added, or are removed. They should be given to elements inside an
array to give them a stable identity.

140
19) What is Props Drilling in React?
Props drilling, in simple terms, is when you have to pass data from a parent
component to a deeply nested child component through multiple layers of
components that don't need that data.

Using Props we normally do this

141
20) What Pure Component in React?
React Pure Components are primarily utilized to prevent unnecessary
re-renders when the component's props and state haven't changed. This
optimization is crucial for enhancing the performance of React applications,
especially as they grow in complexity.

Its is normandy used in class components with extence React.pureComponent


like function component (useMemo).

142
21) How do you validate Forms in React?

143
Formik

● Description: A popular form library for React that makes handling form state, validation,
and submission simpler.
● GitHub: Formik

Yup

● Description: A schema validation library often used with Formik for creating validation
schemas. It helps in validating form fields based on a defined schema.
● GitHub: Yup

React Hook Form

● Description: A minimalistic library that allows you to handle forms using hooks. It's
known for its performance and simplicity, especially for handling uncontrolled
components.
● GitHub: React Hook Form

React Final Form

● Description: A framework-agnostic library for managing form state in React


applications. It focuses on performance and flexibility.
● GitHub: React Final Form

Validator.js

● Description: A library for string validation and sanitization in JavaScript, often used in
combination with other form libraries like Formik.
● GitHub: Validator.js

React-Validation

● Description: A simple validation library for React, providing built-in validation rules and
an easy way to create custom rules.
● GitHub: React-Validation

144
145
146
22) How do you deal with asynchronous operations in React?
For managing side effects, such as API calls, the useEffect hook is commonly used in
functional components. You can perform asynchronous operations inside useEffect and
handle the results accordingly.

147
23) What is the difference between useEffect and useLayoutEffect?

useEffect and useLayoutEffect are both hooks in React used for


managing side effects in functional components. However, they are used in
different scenarios based on when you want the side effects to be applied
in relation to the DOM updates.

Timing of Execution:

● useEffect: Executes after the DOM has been painted (paint phase).
● useLayoutEffect: Executes after the DOM mutations but before the
paint (layout phase).

Use Cases:

● useEffect: Suitable for most side effects that do not need to block the
paint process, such as data fetching and event listeners.
● useLayoutEffect: Suitable for scenarios that require DOM
measurements or direct manipulations that need to occur before the
browser repaints the screen.

Performance Impact:

● useLayoutEffect: Can cause performance issues if used excessively or


improperly, as it blocks the paint process. It should be used sparingly and
only when necessary.
● useEffect: Generally preferred for most side effects due to its
non-blocking nature.

148
149
23) How would you implement routing in a React application?
React Router is a popular library for handling routing and navigation in React
applications. It allows you to define multiple routes and navigate between them easily.
Here’s how to set up routing using React Router:

150
24) Can you explain the concept of "lifting state up"?
Lifting state up is a common pattern in React where state is moved from a child
component to a parent component to allow multiple child components to share
and synchronize the state.

151
25) What is forwardRef in a React ?
forwardRef is a React utility function that enables you to forward refs from a
parent component to a child component. This is often used when you want to
expose a ref to a specific DOM element or a component’s instance within a
functional component.

152
153
26) What are Error boundaries ?
Error boundaries are one of the features in react which allows the developers to catch
the errors during the rendering of component tree, log those errors and handle those
errors without crashing the entire application by displaying a fallback ui.

154
27) What is the Strict mode in react ?
It identifies the commonly occurred bugs in the development time itself.

1. Checks if there are any deprecated apis usage.


2. Checks for deprecated lifecycle methods.
3. Checks if Duplicate keys in list. Warns about Possible memory leaks. etc.

155
29) How do you optimize your react application ?

Code Splitting: Break down large bundles into smaller chunks to reduce initial
load times

Lazy Loading: Load non-essential components\asynchronously to prioritize


critical content.

Caching and Memoization: Cache data locally or use memoization libraries to


avoid redundant API calls and computations.

Memoization: Memoize expensive computations and avoid unnecessary


re-renders using tools like React.memo and useMemo

Optimized Rendering: Use shouldComponentUpdate, PureComponent, or


React.memo to prevent unnecessary re-renders of components.

Virtualization: Implement virtual lists and grids to render only the visible
elements, improving rendering performance for large datasets.

Server-Side Rendering (SSR): Pre-render content on the server to improve initial


page load times and enhance SEO.

Bundle Analysis: Identify and remove unused dependencies, optimize images,


and minify code to reduce bundle size.

Performance Monitoring: Continuously monitor app performance using tools like


Lighthouse, Web Vitals, and browser DevTools.

CDN Integration: Serve static assets and resources from Content Delivery
Networks (CDNs) to reduce latency and improve reliability.

156
30) What are Portals in react ?
Portals are the way to render the child components outside of the parent’s dom
hierarchy.

We mainly need portals when a React parent component has a hidden value of overflow
property(overflow: hidden) or z-index style, and we need a child component to openly
come out of the current tree hierarchy. It is commonly used in Modals, tooltips, loaders,
notifications toasters. This helps in improving the performance of application

157
32) Differences between dependencies and devDependencies ?

33. What is a Container/Presentational pattern ?

158
34) What are the various design patterns in react ?
Compound pattern

HOC Pattern Render

props pattern

Container/Presentational pattern

35) What is render props pattern ?

https://javascriptpatterns.vercel.app/patterns/react-patterns/render-props

36) What is the compound pattern ?


By using this compound pattern we will create multiple components that
work together to perform a single task. We can achieve this using context
api.

This promotes separation of concerns between parent and child


components, promotes reusability of logic and maintainability.

159
37) What are the differences between client side and server side
rendering ?

160
39) difference between Package.json and Package.lock.json ?

40) What is a react-router ?


React-router is a javascript library which is used to implement routing in react
applications. It allows us to navigate between views or pages with out refreshing
the page.

161
162
📧[email protected] 🌐Portfolio LinkedIn GitHub

163

You might also like