Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 286

HTML And CSS

Input Types and there use cases?


HTML provides a variety of input types that can be used to collect different kinds of
user data. Here is an overview of all the input types, along with their exact use cases,
and additional details for select, radio, and checkbox elements.
Textual Input Types
text
<input type="text" placeholder="Enter your name">
Use Case: General text input.
Example: Collecting names, addresses, or other freeform text data.
password
<input type="password" placeholder="Enter your password">
Use Case: Secure text input where entered characters are masked.
Example: Password fields in login forms.
email
<input type="email" placeholder="Enter your email">
Use Case: Email address input with built-in validation.
Example: Collecting user email addresses for newsletters or account creation.
url
<input type="url" placeholder="Enter your website URL">
Use Case: URL input with built-in validation.
Example: Collecting website URLs for profiles or links.
tel
<input type="tel" placeholder="Enter your phone number">
Use Case: Telephone number input.
Example: Collecting phone numbers for contact forms.
search
<input type="search" placeholder="Search...">
Use Case: Search queries input.
Example: Search bars on websites.
number
<input type="number" placeholder="Enter a number" min="1" max="10">
Use Case: Numerical input with optional constraints.
Example: Collecting age, quantity, or other numerical data.
range
<input type="range" min="1" max="100" step="1">
Use Case: Slider input for a range of values.
Example: Volume control, brightness setting.
Date and Time Input Types
date
<input type="date">
Use Case: Date input.
Example: Collecting birthdates or appointment dates.
month
<input type="month">
Use Case: Month and year input.
Example: Selecting a month for a subscription start.
week
<input type="week">
Use Case: Week input.
Example: Selecting a week for event scheduling.
time
<input type="time">
Use Case: Time input.
Example: Collecting appointment times or scheduling.
datetime-local
<input type="datetime-local">
Use Case: Date and time input.
Example: Scheduling events with both date and time.
Specialized Input Types
color
<input type="color">
Use Case: Color picker input.
Example: Selecting colors for themes or artwork.
file
<input type="file">
Use Case: File upload input.
Example: Uploading documents, images, or other files.
Button Input Types
submit
<input type="submit" value="Submit">
Use Case: Submit form data.
Example: Submit button in forms.
reset
<input type="reset" value="Reset">
Use Case: Reset form data to initial values.
Example: Reset button in forms.
button
<input type="button" value="Click Me">
Use Case: General button without form submission.
Example: Custom actions like toggling visibility or triggering scripts.
Select Element
The <select> element is used to create a dropdown list.
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Use Case: Provides a list of options for the user to choose from.
Example: Choosing a car brand, selecting a country, or picking a category.
Radio Buttons
Radio buttons allow the user to select one option from a set.
<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>
Use Case: Selecting a single option from a group.
Example: Choosing gender, selecting a payment method, or picking a subscription
plan.
Checkboxes
Checkboxes allow the user to select one or more options from a set.
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
Use Case: Selecting multiple options from a group.
Example: Choosing interests, selecting multiple items for purchase, or agreeing to
terms and conditions.
Full Example
Here’s a full example that incorporates various input types:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Example</title>
</head>
<body>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br><br>

<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone">
<br><br>

<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
<br><br>
<label for="appt">Appointment time:</label>
<input type="time" id="appt" name="appt">
<br><br>

<label for="favcolor">Favorite Color:</label>


<input type="color" id="favcolor" name="favcolor">
<br><br>

<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100">
<br><br>

<label for="file">Upload a file:</label>


<input type="file" id="file" name="file">
<br><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select>
<br><br>

<p>Gender:</p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<br><br>

<p>Hobbies:</p>
<input type="checkbox" id="sports" name="hobbies" value="sports">
<label for="sports">Sports</label>
<br>
<input type="checkbox" id="music" name="hobbies" value="music">
<label for="music">Music</label>
<br>
<input type="checkbox" id="reading" name="hobbies" value="reading">
<label for="reading">Reading</label>
<br><br>

<input type="submit" value="Submit">


</form>
</body>
</
html>***********************************************************
*****
1) Box Model? CSS Animation, SCSS variables and mixins in CSS?
****************************************************************
2) Create a Triangle using CSS?
****************************************************************
3) CSS flex vs CSS grid?
Grid:
 CSS Grid Layout, is a two-dimensional grid-based layout system with rows
and columns, making it easier to design web pages without having to use
floats and positioning.
 Like tables, grid layout allows us to align elements into columns and rows.
 To get started you have to define a container element as a grid with display:
grid, set the column and row sizes with grid-template-columns and grid-
template-rows, and then place its child elements into the grid with grid-
column and grid-row.
Flexbox:
 The CSS Flexbox offers a one-dimensional layout. It is helpful in allocating
and aligning the space among items in a container (made of grids).
 It works with all kinds of display devices and screen sizes.
 To get started you have to define a container element as a grid with
display: flex;
One Vs Two Dimension:
 Grid is made for two-dimensional layout while Flexbox is for one. This
means Flexbox can work on either row or columns at a time, but Grids can
work on both.
 Flexbox, gives you more flexibility while working on either element (row or
column). HTML markup and CSS will be easy to manage in this type of
scenario.
 GRID gives you more flexibility to move around the blocks irrespective of
your HTML markup.
Content-First vs Layout-First:
 Major Uniqueness between Flexbox and Grids is that the former works on
content while the latter is based on the layout.
 The Flexbox layout is best suited to application components and small-scale
layouts,
 while the Grid layout is designed for larger-scale layouts that are not linear in
design.
Difference Between Grid and Flexbox:
1. Dimensionality and Flexibility:
 Flexbox offers greater control over alignment and space distribution between
items. Being one-dimensional, Flexbox only deals with either columns or
rows.
 Grid has two-dimension layout capabilities which allow flexible widths as a
unit of length. This compensates for the limitations in Flex.
2. Alignment:
 Flex Direction allows developers to align elements vertically or horizontally,
which is used when developers create and reverse rows or columns.
 CSS Grid deploys fractional measure units for grid fluidity and auto-keyword
functionality to automatically adjust columns or rows.
3. Item Management:
 Flex Container is the parent element while Flex Item represents the children.
The Flex Container can ensure balanced representation by adjusting item
dimensions. This allows developers to design for fluctuating screen sizes.
 Grid supports both implicit and explicit content placement. Its inbuilt
automation allows it to automatically extend line items and copy values into
the new creation from the preceding item.
Conclusion
 CSS Grids helps you create the outer layout of the webpage. You can build
complex as well responsive design with this. This is why it is called ‘layout
first’.
 Flexbox mostly helps align content & move blocks.
 CSS grids are for 2D layouts. It works with both rows and columns.
 Flexbox works better in one dimension only (either rows OR columns).
 It will be more time saving and helpful if you use both at the same time.
****************************************************************
4) Relative vs Absolute?
 Relative Position:
Setting the top, right, bottom, and left properties of an element with
position: relative;
property will cause it to adjust from its normal position.
The other objects or elements will not fill the gap.
Syntax: position: relative;
 Absolute Position:
An element with position: absolute; will cause it to adjust its position
with respect to its parent.
If no parent is present, then it uses the document body as parent.
Syntax: position: absolute;
 Fixed Position:
Position: fixed;
property applied to an element will cause it to always stay in the same
place even if the page is scrolled.
To position the element we use top, right, bottom, left properties.
Syntax: Position: fixed;

****************************************************************
5) If I have 4 divs and nested to place it side by side , how can I do this?
<div class="wrap">
<div id="a" class="resp">aaaaaa</div>
<div id="b" class="resp">bbbbbb</div>
<div id="c" class="resp">ccccccc</div>
<div id="d" class="resp">dddddd</div>
</div>
.wrap {text-align: center; margin: 15px auto;}
.resp {display: inline-block; text-align: left; width: 21%; margin-right:
1%;}
****************************************************************
6) Block vs inline?
Difference between Inline and Block elements:
Inline Elements Block Elements
Inline elements occupy only sufficient Block Elements occupy the full width
width required. irrespective of their sufficiency.
Inline elements don’t start in a new line. Block elements always start in a line.
Inline elements allow other inline Block elements doesn’t allow
elements to sit behind. other elements to sit behind
Inline elements don’t have top and Block elements have top and bottom
bottom margin margin.
****************************************************************
7) HTML5 new features?
 HTML5 introduced several new features and enhancements over its
predecessor, HTML4. Some key HTML5 features include:
1) Semantic Elements:
Introduction of semantic elements such as <header>, <nav>, <section>,
<article>, <aside>, and <footer>. These elements provide a more meaningful
structure to web documents, aiding in better accessibility and SEO.
2) Audio and Video Elements:
<audio> and <video> elements allow embedding and playing audio and video
content directly in the browser without relying on plugins like Flash.
<audio controls>
<source src="audio.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
<video width="640" height="360" controls>
<source src="video.mp4" type="video/mp4">
Your browser does not support the video element.
</video>
3) Canvas Element:
The <canvas> element provides a drawing surface for graphics and animations
using JavaScript.
<canvas id="myCanvas" width="300" height="150"></canvas>
4) SVG (Scalable Vector Graphics):
Support for inline SVG, allowing the inclusion of vector graphics directly in
the HTML document.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3"
fill="red" />
</svg>
5) Form Enhancements:
New input types like <input type="date">, <input type="color">, <input
type="number">, and more.
The <datalist> element provides a predefined list of options for other form
controls.
6) Local Storage and Session Storage:
The localStorage and sessionStorage APIs allow web applications to store data
locally on the user's device.
localStorage.setItem('key', 'value');
let storedValue = localStorage.getItem('key');
7) Web Storage:
Introduction of the localStorage and sessionStorage for storing key/value pairs
persistently or for the duration of a page session.
localStorage.setItem('key', 'value');
let storedValue = localStorage.getItem('key');
8) Web Workers:
Web Workers allow the execution of JavaScript code in the background,
enabling multi-threading for improved performance.
// Create a new worker
const worker = new Worker('worker.js');
9) Geolocation API:
The Geolocation API provides access to the user's location information.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
10) Drag and Drop API:
The Drag and Drop API allows elements to be dragged and dropped within a
web page.
<div id="draggable" draggable="true">Drag me!</div>
These features, among others, contribute to the enhanced functionality,
performance, and interactivity of modern web applications built with HTML5.
*********************************************************************
8) How Video Works?
 In HTML, you can embed videos using the <video> element. The <video>
element provides a standard way to include videos on web pages. Here's a basic
example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Video Example</title>
</head>
<body>

<video width="640" height="360" controls>


<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>
Let's break down the key parts of this example:
<video> element: This is the container for the video. The width and height
attributes set the dimensions of the video player, and the controls attribute adds
playback controls (play, pause, volume, etc.).
<source> element: This is used to specify the video file and its type. In this
example, it points to an MP4 video file. You can include multiple <source>
elements to provide different video formats for broader browser compatibility.
Fallback text: The text "Your browser does not support the video tag." is
displayed if the browser does not support the <video> element.
Attributes like width and height: These attributes set the dimensions of the
video player. You can adjust these values based on your design preferences.
controls attribute: This attribute adds the default playback controls to the
video player.
You need to replace "example.mp4" with the actual path to your video file.
Additionally, providing multiple source elements with different formats (e.g.,
MP4, WebM, Ogg) is a good practice for better cross-browser compatibility.
Here's a brief overview of some common attributes for the <video> element:
autoplay: The video starts playing as soon as it is loaded.
loop: The video restarts from the beginning when it reaches the end.
muted: The video plays without sound.
poster: A still image displayed before the video starts playing.
<video width="640" height="360" controls autoplay loop muted
poster="thumbnail.jpg">
<!-- Source elements go here -->
</video>
Keep in mind that different browsers may support different video formats.
Providing multiple sources with different formats increases the chances of
compatibility across various browsers.
****************************************************************
9) CSS3 new features?
Background image:

 In css3 lots of CSS new features are available through which we can set any
kind of background images into our website.
 And there are almost seven or eight background properties are adds through
which we can easily use the URL of the background-image property.
Background size:

 This property is mainly use to set the size of your background property.
 And feature is not actually adds into your background image into full size.
 There are many sizes into the background size property and if we use the cover
attribute then the size or image cover into the full size.
Multiple columns:

 Css3 also provide an important feature in terms of the column layout section
and this feature is actually not provided in the css older versions.
 And with the help of this feature we can set column width, column count etc.
Picture transparency:

 If you want to display your picture inside the websites into a transparent way
then you have to definitely used the .png or .gif extension to save the picture
and you can easily present your image into more transparent way.
 There are normally two transparent value 0 and 1.
 Here 0 is use for totally transparent and 1 is use for the opaque option css3 new
features
CSS3 new features :
Corners:
One of the main advantage of using the css3 is the rounded corner feature
Borders:

 With the help of css3, we can define and present our borders in a more
attractive way.
 And in the CSS older versions we normally use the two types of images of
border styles one is dash styles and another is solid.
 But with the help of css3 we can define the border images into much more
attractive ways. Such as in daashed styles, in dotted styles, in solid styles , or
also in rounded styles.
Gradient:
Gradients are also very useful in css3. Css3 provides us some of the new
features through which we can easily add any images and we can also apply
any of the transparency into our codes and these are also useful with the colors
also.
****************************************************************
10) Difference between CSS grid and bootstrap?

Basis of CSS Grid Bootstrap


Comparison

It has a markup that is It is necessary to have a div tag for


clearer and easier to read. each row, as well as to define the
Markup The layout of the grid is not class tier inside each div element in
done in the HTML but order to establish the layout. It makes
rather in the CSS. the code lengthier.

Even if HTML does not Using established class tiers, one is


change, all that has to be able to independently design the
done to modify the CSS is layout of the content area for a variety
Responsiveness to add various media of different device sizes. However,
queries and describe the the markup will get more
grid layout for each HTML cumbersome as the number
element. of div classes will rise.

strong support from the vast Because the accompanying files for
majority of browsers and the stylesheet need to be downloaded,
Page Load versions. There is no need the speed at which the website loads
Speed to download anything, and is slow.
the website loads much
more quickly.

It provides a flexible layout Because the grid is divided into 12


with no restrictions on the columns, it is impossible to actualize
Column number of columns. a layout that does not sum up to 12.
Limitation Because of this, it is not
difficult to have any
number of columns.
****************************************************************
11) Difference between bootstrap 3 and 4?
Flexbox:
Bootstrap 3: Based on the traditional box model.
Bootstrap 4: Introduced a migration to Flexbox, providing more powerful and
flexible layout options.
Grid System:
Bootstrap 3: Used a 12-column grid system.
Bootstrap 4: Retained the 12-column grid system but switched to Flexbox,
offering improved alignment and distribution options.
Mobile-First Design:
Bootstrap 3: Mobile-first design approach but not fully responsive by default.
Bootstrap 4: Embraces a fully responsive and mobile-first design philosophy.
Card Component:
Bootstrap 3: Did not have a dedicated card component.
Bootstrap 4: Introduced the Card component, providing a flexible container for
content, including images, text, links, and more.
Navbar:
Bootstrap 3: Used a fixed-top navbar by default.
Bootstrap 4: Defaulted to a responsive navbar with improved customization
options.
Typography:
Bootstrap 3: Utilized the Glyphicons icon set for additional UI elements.
Bootstrap 4: Dropped Glyphicons and encouraged the use of third-party icon
libraries like Font Awesome.
Utilities and Classes:
Bootstrap 3: Used .col-xs-*, .col-sm-*, .col-md-*, .col-lg-* for responsive
classes.
Bootstrap 4: Simplified the classes to .col-* for a more straightforward
approach.
Removal of Panels:
Bootstrap 3: Featured the panel component for creating containers with a
border.
Bootstrap 4: Removed panels, encouraging the use of the new Card component.
Revised Components:
Bootstrap 4: Introduced new and revised components, including the utility
classes for spacing, responsive embeds, and more.
Improved Documentation:
Bootstrap 4: Came with improved and more organized documentation, making
it easier for developers to find information and use the framework effectively.
Sass Support:
Bootstrap 3: Used Less as the preprocessor for stylesheets.
Bootstrap 4: Switched to Sass, offering enhanced modularity and
maintainability.
****************************************************************
12) Display: inline-block / block [hint: span/ div]
 display: inline-block brought a new way to create side by side boxes that
collapse and wrap properly depending on the available space in the containing
element. It makes layouts that were previously accomplished with floats
easier to create. No need to clear floats anymore.
 Compared to display: inline, the major difference is that inline-block allows to
set a width and height on the element. Also, with display: inline, top and
bottom margins & paddings are not respected, and with display: inline-
block they are.

Now, the difference between display: inline-block and display: block is that,
with display: block, a line break happens after the element, so a block element
doesn’t sit next to other elements. Here are some visual examples:

****************************************************************
13) What do you mean by web accessibility?
Web accessibility means that websites, tools, and technologies are designed
and developed so that people with disabilities can use them. More specifically,
people can:
 perceive, understand, navigate, and interact with the Web
 contribute to the Web
Web accessibility encompasses all disabilities that affect access to the Web,
including
 auditory
 Cognitive
 Neurological
 Physical
 Speech
 visual
Web accessibility also benefits people without disabilities, for example:
 people using mobile phones, smart watches, smart TVs, and other devices with
small screens, different input modes, etc.
 older people with changing abilities due to ageing
 people with “temporary disabilities” such as a broken arm or lost glasses
 people with “situational limitations” such as in bright sunlight or in an
environment where they cannot listen to audio
 people using a slow Internet connection, or who have limited or expensive
bandwidth
****************************************************************
12) Mention some html5 tags and properties
 HTML5 introduced several new elements and attributes to enhance the
structure, semantics, and functionality of web documents. Here are some
HTML5 tags and properties:
HTML5 Tags:
<header>: Represents the header of a section or a page.
<nav>: Represents a navigation menu.
<section>: Represents a thematic grouping of content.
<article>: Represents a self-contained piece of content that could be distributed
and reused independently.
<aside>: Represents content that is tangentially related to the content around it
(like a sidebar).
<footer>: Represents the footer of a section or a page.
<main>: Represents the main content of the document.
<figure>: Represents any content that is referenced from the main content, such
as images, charts, and code snippets.
<figcaption>: Represents a caption or legend for a <figure> element.
<mark>: Represents text highlighted for reference or notation.
<progress>: Represents the completion progress of a task.
<time>: Represents a specific period in time or a range of time.
HTML5 Attributes/Properties:
class and id attributes: Used for styling and identifying elements with CSS and
JavaScript.
data-* attributes: Custom attributes for storing extra information, often used
with JavaScript.
contenteditable attribute: Allows the user to edit the content of an element.
autocomplete attribute: Specifies whether a form or input field should have
autocomplete enabled or disabled.
placeholder attribute: Provides a hint or example text in an input field.
required attribute: Specifies that an input field must be filled out before
submitting a form.
autofocus attribute: Specifies that an input field should automatically get focus
when the page loads.
async and defer attributes: Used with <script> tags to control script execution
timing.
download attribute: Prompts the user to download a linked resource rather than
navigating to it.
role attribute: Specifies the role of an element for accessibility purposes.
aria-* attributes: A set of attributes used for enhancing accessibility by
providing additional information to assistive technologies.
These are just a few examples, and HTML5 introduced many more elements
and attributes. Using these elements and attributes helps create cleaner, more
semantic, and accessible markup for modern web development.
****************************************************************
13) Diff between async and defer on loading script
async and defer both load JavaScript asynchronously without render blocking,
but async executes as soon as possible while defer runs in sequence toward the
end of the loading process, just before the DOMContentLoaded event.
Async :
 Downloads in the background at a low priority (same as defer)
 Can interrupt page rendering to execute
 Executes as soon as possible and in no particular order
Defer:
 Downloads in the background at a low priority (same as async)
 Won't interrupt page rendering to execute
 Executes in sequence just before the DOMContentLoaded event
****************************************************************
14) What are rem and em properties in css
 In CSS, rem, em, and px are units of measurement used to define the size of
elements, such as font sizes, margins, padding, and more. Here's a brief
explanation of the differences between rem, em, and px:
px (Pixels):
 px is an absolute unit of measurement. One pixel is a single dot on a screen,
and its size is fixed.
 It is not relative to any other element's size, and the actual size might vary
depending on the device's display density (e.g., a high-density "Retina" display
may render pixels more densely).
 Example: font-size: 16px;
em:
 em is a relative unit of measurement. It is based on the font-size of the parent
element.
 If the font-size of an element is set to 1em, it equals the font-size of its parent.
If it's set to 2em, it's twice the font-size of its parent, and so on.
 Example: If the parent element's font-size is 16px, then 1em is equivalent to
16px.
rem (Root em):
 rem is also a relative unit, but it is relative to the font-size of the root element
(html)
 Unlike em, which can cascade and compound based on the parent-child
relationship, rem is not affected by the parent's font-size.
 It provides a more predictable and consistent way to set sizes across the entire
page.
 Example: font-size: 1.5rem; means 1.5 times the font-size of the root element.
Example:
html {
font-size: 16px; /* Set a base font size for the root element */
}
body {
font-size: 1rem; /* 1rem is equal to 16px (root element's font-size) */
}
h1 {
font-size: 2em; /* 2em is twice the font-size of the parent (body), so 32px
*/
}
p{
font-size: 1.5rem; /* 1.5rem is 1.5 times the root font-size, so 24px */
}
 In summary, px is an absolute unit, em is relative to the font-size of its parent,
and rem is relative to the font-size of the root element. The choice of which
unit to use depends on the specific design requirements and how you want
styles to cascade through the document hierarchy.
****************************************************************
15) What are diff ways you can make webpage responsive
 Creating a responsive webpage means designing it in a way that allows the
layout and content to adapt to different screen sizes and devices. Here are
various techniques and tools you can use to make a webpage responsive:
1) Media Queries:
Use CSS media queries to apply different styles based on the screen size,
resolution, or other characteristics. This allows you to create responsive
layouts for various devices.
@media screen and (max-width: 600px) {
/* Styles for screens up to 600px wide */
}
@media screen and (min-width: 601px) and (max-width: 1024px) {
/* Styles for screens between 601px and 1024px wide */
}
@media screen and (min-width: 1025px) {
/* Styles for screens 1025px wide and above */
}
2) Viewport Meta Tag:
Use the viewport meta tag to control the viewport width and scaling on mobile
devices. This tag is essential for ensuring proper rendering on various screen
sizes.
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
3) Flexible Grids (Flexbox and CSS Grid):
Utilize Flexbox and CSS Grid for creating flexible and responsive grid
layouts. They allow for easy rearrangement of content based on the
available space.
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1;
}
4) Fluid Images:
Make images responsive by using the max-width: 100% CSS property,
ensuring that images scale within their container.
img {
max-width: 100%;
height: auto;
}
5) Relative Units (em, rem, vw, vh):
Use relative units instead of fixed units for font sizes and dimensions. This
allows content to scale based on the user's preferences or screen size.
body {
font-size: 16px;
}
h1 {
font-size: 2em;
}
6) CSS Frameworks:
Consider using CSS frameworks like Bootstrap or Foundation, which
provide responsive design components and grids that you can easily
integrate into your project.
7) Responsive Images:
Implement responsive images using the srcset attribute, allowing the
browser to choose the appropriate image based on the user's device and
screen resolution.
<img src="small.jpg" srcset="medium.jpg 800w, large.jpg 1200w"
alt="Responsive Image">
8) Media Query Breakpoints:
Establish breakpoints in your media queries to address specific screen sizes
and adjust styles accordingly. This helps ensure a smooth transition
between different layouts.
@media screen and (max-width: 480px) {
/* Styles for small screens */
}
@media screen and (min-width: 481px) and (max-width: 768px) {
/* Styles for medium screens */
}
By combining these techniques, you can create a responsive webpage
that adapts to various devices and screen sizes, providing a better user
experience across different platforms.
****************************************************************
16) When a response is sent from server to browser what gets loaded first?
HTML? CSS or JS?
 When a response is sent from the server to the browser, the browser processes
the received data in the order it is received. Generally, the order of loading and
processing is as follows:
 HTML: The HTML content is the first to be loaded and processed. The
browser parses the HTML document to construct the Document Object Model
(DOM), which represents the structure of the webpage.
 CSS: Once the browser encounters a CSS link or style tag in the HTML, it
starts fetching and processing the CSS. The CSS is used to style the HTML
elements and is applied to the DOM, affecting the visual presentation of the
page.
 JavaScript: After the HTML and CSS have been loaded and the DOM is
constructed, the browser starts loading and executing JavaScript. JavaScript
can manipulate the DOM, modify styles, and add interactivity to the webpage.
The execution of JavaScript can be synchronous (blocking) or asynchronous,
depending on how it's included in the HTML.
 It's important to note that the order of loading doesn't necessarily mean that the
entire HTML document must be loaded before CSS or JavaScript. Browsers
use a technique called "parsing and rendering" to start rendering parts of the
page while still loading resources asynchronously.
 Additionally, the loading and execution of resources can be influenced by
various factors, such as the placement of script tags, the use of the async and
defer attributes for scripts, and whether resources are loaded from the cache or
fetched from the server.
 In modern web development, it's common to optimize the loading process by
placing CSS in the head of the document to ensure styles are applied early, and
JavaScript is often placed at the end of the body or with the defer attribute to
prevent blocking the rendering of the page.
 https://blog.logrocket.com/how-browser-rendering-works-behind-scenes/
****************************************************************
17) Uses of mixins and what are diff css libraries you have used?
 Mixins encourage code reuse and can be used to avoid the inheritance
ambiguity that multiple inheritance can cause (the "diamond problem"), or to
work around lack of support for multiple inheritance in a language.
 A mixin can also be viewed as an interface with implemented methods.
****************************************************************
18) Html a semantic tag?
 Semantic HTML elements are those that clearly describe their meaning in a
human- and machine-readable way.
 Elements such as <header>, <footer> and <article> are all considered semantic
because they accurately describe the purpose of the element and the type of
content that is inside them.
The semantic elements added in HTML5 are:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
****************************************************************
19) hv u heard about specificity in css?

 When more than one set of CSS rules apply to the same element, the browser
will have to decide which specific set will be applied to the element. The rules
the browser follows are collectively called Specificity

Specificity Rules include:


 CSS style applied by referencing external stylesheet has lowest precedence and
is overridden by Internal and inline CSS.
 Internal CSS is overridden by inline CSS.
 Inline CSS has highest priority and overrides all other selectors.
Specificity in CSS refers to the set of rules that determine which style declarations
are applied to an element when there are conflicting styles. The browser uses the
specificity of selectors to decide which styles should take precedence. Specificity
is calculated based on the different components of a selector. The higher the
specificity, the more weight a style rule carries.
Here's a breakdown of how specificity is calculated:
Inline Styles:
Inline styles have the highest specificity. They are applied directly to an element
using the style attribute.
<div style="color: red;">This is a red text.</div>
ID Selectors:
ID selectors have a higher specificity compared to class selectors or element
selectors
css
myElement {
color: blue;
}
Class, Attribute, and Pseudo-Class Selectors:
Class selectors, attribute selectors, and pseudo-class selectors have equal
specificity. The count of each of these selectors in the overall selector contributes
to specificity.
.myClass {
color: green;
}
[type="text"] {
font-size: 16px;
}
:hover {
background-color: yellow;
}
Element and Pseudo-Element Selectors:
Element selectors and pseudo-element selectors have the lowest specificity.
p{
font-weight: bold;
}
::before {
content: "Before";
}
When comparing two selectors, the specificity is typically represented as a four-
part value, such as 0,0,0,0, where each part corresponds to inline styles, ID
selectors, class/attribute/pseudo-class selectors, and element/pseudo-element
selectors, respectively.
Selector #myElement has specificity 0,1,0,0 (one ID selector).
Selector .myClass has specificity 0,0,1,0 (one class selector).
Selector p has specificity 0,0,0,1 (one element selector).
If two conflicting rules have the same specificity, the one that comes later in the
stylesheet takes precedence, following the principle of the "last rule wins."
Understanding specificity is crucial for writing maintainable and predictable CSS
code, and it helps avoid unexpected styling issues.
https://www.geeksforgeeks.org/css-specificity/
****************************************************************
20) What is box modal?

 The CSS box model is a container that contains multiple properties including
borders, margin, padding, and the content itself.
 It is used to create the design and layout of web pages.
 It can be used as a toolkit for customizing the layout of different elements.
 The web browser renders every element as a rectangular box according to the
CSS box model.
 Box-Model has multiple properties in CSS. Some of them are given below:
content:
This property is used to displays the text, images, etc, that can be sized using the
width & height property.
padding:
This property is used to create space around the element, inside any defined
border.
border:
This property is used to cover the content & any padding, & also allows to set
the style, color, and width of the border.
margin:
This property is used to create space around the element ie., around the border
area.
****************************************************************
21) Why we use DOCTYPE in html?

 The HTML document type declaration, also known as DOCTYPE, is the first
line of code required in every HTML or XHTML document.
 The DOCTYPE declaration is an instruction to the web browser about what
version of HTML the page is written in.
 This ensures that the web page is parsed the same way by different web
browsers.
****************************************************************
22) What versions of css have u used or been working?
 CSS-3
****************************************************************
23) sudo classes and sudo element? In a div displaying 4 is or n no of
paragraph , I want to display specific symbol ($) before every p tag
 Pseudo-Class
 A pseudo-class represents a state of a selector like :hover, :active, :last-
child,etc.
 These start with a single colon(:).
 The syntax of CSS pseudo-class is as follows
 :pseudo-class{
attribute: /*value*/
}
 Pseudo-Element
 Similarly, a pseudo-element is used to select virtual elements like ::after,
::before, ::first-line, etc.
 These start with a double colon(::).
 The syntax of CSS pseudo-element is as follows
 ::pseudo-element{
attribute: /*value*/
}
****************************************************************
24) Html attributes?

 An attribute is used to define the characteristics of an HTML element and is


placed inside the element's opening tag.
 All attributes are made up of two parts − a name and a value
 The name is the property you want to set. For example, the paragraph <p>
element in the example carries an attribute whose name is align, which you can
use to indicate the alignment of paragraph on the page.
 The value is what you want the value of the property to be set and always put
within quotations. The below example shows three possible values of align
attribute: left, center and right.
<body>
<p align = "left">This is left aligned</p>
<p align = "center">This is center aligned</p>
<p align = "right">This is right aligned</p>
</body>
****************************************************************
25) position in css?
1) Static
 Default value. Elements render in order, as they appear in the document flow

2) absolute
 The element is positioned relative to its first positioned (not static) ancestor
element
3) fixed
 The element is positioned relative to the browser window
4) Relative
 The element is positioned relative to its normal position, so "left:20px" adds
20 pixels to the element's LEFT position
5) sticky
 The element is positioned based on the user's scroll position
 A sticky element toggles between relative and fixed, depending on the scroll
position.
 It is positioned relative until a given offset position is met in the viewport -
then it "sticks" in place (like position:fixed).
6) Initial
 Sets this property to its default value. Read about initial
7) Inherit
 Inherits this property from its parent element. Read about inherit
****************************************************************
26) diff between display none and visibility hidden
 The visibility: “hidden”; property is used to specify whether an element is
visible or not in a web document but the hidden elements take up space in the
web document.
 The visibility is a property in CSS that specifies the visibility behaviour of an
element.
 The display property in CSS defines how the components (such as div,
hyperlink, heading, etc) are going to be placed on the web page.
 The display: “none” property is used to specify whether an element exists or
not on the website.
****************************************************************
27) Is it possible to change inline element as block
 You can change the visual presentation of an element using the CSS display
property. For example, by changing the value of display from "inline" to
"block" , you can tell the browser to render the inline element in a block
box rather than an inline box, and vice versa
****************************************************************
28) Meta tag in Html
 The <meta> tag is used to provide such additional information.
 This tag is an empty element and so does not have a closing tag but it carries
information within its attributes.
 You can include one or more meta tags in your document based on what
information you want to keep in your document but in general, meta tags do
not impact physical appearance of the document so from appearance point of
view, it does not matter if you include them or not.
****************************************************************
29) Opacity purpose?
 The opacity() function is an inbuilt function which is used to apply a filter to
the image to set the transparency of the image.
****************************************************************
30) How you make particular element at center of pages
 1) <article>
<div class=”classic”>Hello</div>
<article>
.classic {
Position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%)
}
2) <article class=”flex”>
<div>hello</div\>
<article>
.flex{
display: flex;
align-items: center;
justify-content: center;
}
3) <article class=”grid”>
<div>Hello</div>
</article>
.grid {
display: grid;
place-items: center;
}
****************************************************************
31) How to determine whether browser support particular features like flux or
grid?
 To determine whether a browser supports specific features like Flexbox or CSS
Grid, you can use feature detection. Here's how you can do it using JavaScript:
Flexbox Feature Detection:
if ('flex' in document.documentElement.style || 'webkitFlex' in
document.documentElement.style) {
// Browser supports Flexbox
console.log('Flexbox is supported');
} else {
// Browser does not support Flexbox
console.log('Flexbox is not supported');
}
The reason for checking both 'flex' and 'webkitFlex' is to account for older
versions of WebKit browsers (like Safari) that used the 'webkit' prefix.
CSS Grid Feature Detection:
if ('grid' in document.documentElement.style || 'msGrid' in
document.documentElement.style) {
// Browser supports CSS Grid
console.log('CSS Grid is supported');
} else {
// Browser does not support CSS Grid
console.log('CSS Grid is not supported');
}
Similar to Flexbox, we check for 'grid' and 'msGrid' to cover older versions of
browsers (like Internet Explorer) that used the 'ms' prefix.

These checks are based on the fact that the style properties associated with
Flexbox and CSS Grid are present in the document.documentElement.style
object.

Additionally, you might consider using a library like Modernizr, which


simplifies feature detection across a wide range of HTML5 and CSS3 features:
if (Modernizr.flexbox) {
// Browser supports Flexbox
console.log('Flexbox is supported');
} else {
// Browser does not support Flexbox
console.log('Flexbox is not supported');
}
if (Modernizr.grid) {
// Browser supports CSS Grid
console.log('CSS Grid is supported');
} else {
// Browser does not support CSS Grid
console.log('CSS Grid is not supported');
}
Remember that feature detection is generally preferable to browser sniffing for
better code flexibility and future-proofing.
****************************************************************
32) Why we need to use clear property when using float?

 The clear property is used to specify which side of floating elements are not
allowed to float.
 It sets or returns the position of the element in relation to floating objects.
 If the element can fit horizontally in the space next to another element which is
floated, it will.
Syntax:
clear: none | left | right | both |initial;
none: It has a default value. It allows element are float on both the sides.
left: This property specifies that elements are not allowed to Float on the left
side in relation to other element.
right: It means elements are not allowed to float on the right side.
both: It means floating elements are not allowed to float on the both sides.
initial: It sets the property to its default value.
****************************************************************
33) What is BOM? Explain Hierarchy
BOM stands for Browser Object Model. Unlike DOM, there is no standard
defined for BOM, hence different browsers implement it in different ways.
Typically, the collection of browser objects is collectively known as the
Browser Object Model.
BOM's main task is to manage browser windows and enable communication
between the windows. Each HTML page that is loaded into a browser window
becomes a Document object and document object is an object in the BOM. You
can say BOM is a superset of DOM. BOM has many objects, methods, and
properties that are not the part of the DOM structure.
The important BOM objects are as:
document
location
history
navigator
screen
frames
****************************************************************
Interview Questions React:
What are the different fundamental blocks of react?
 1. Component
2. JSX
3. State
4. Props
5. LifeCycle Methods
6. Hooks
7. Refs
8. VirtualDOM
9. Context
10. Events

*********************************************************************
1. What is React Context?
 Context provides a way to pass data through the component tree without having
to pass props down manually at every level.
*********************************************************************
2. What are the diff ways to add CSS in your react app?
 In a React application, there are several ways to add CSS styles. The choice of
method depends on the project requirements, structure, and personal
preferences. Here are some common ways to add CSS to a React app:
1. Inline Styles:
You can apply styles directly within the JSX using the style attribute. This
approach is useful when styles are dynamic or depend on component state.
import React from 'react';
const MyComponent = () => {
const textStyle = {
color: 'blue',
fontSize: '16px',
};
return (
<div style={textStyle}>
This text has inline styles.
</div>
);
};
export default MyComponent;
2. Internal Stylesheets:
Define styles within the same JavaScript/JSX file using template literals or
separate variables.
import React from 'react';
const MyComponent = () => {
const styles = `
.container {
background-color: #f0f0f0;
padding: 10px;
}
`;
return (
<div className="container" style={{ border: '1px solid #ccc' }}>
<style>{styles}</style>
Content goes here.
</div>
);
};
export default MyComponent;
3. External Stylesheets:
Create a separate CSS file and import it into your React component. This is a
common and modular approach.
// MyComponent.jsx
import React from 'react';
import './MyComponent.css';
const MyComponent = () => {
return (
<div className="container">
Content goes here.
</div>
);
};
export default MyComponent;
/* MyComponent.css */
.container {
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
}
4. CSS Modules:
CSS Modules allow you to locally scope your CSS class names, preventing
global naming conflicts. The styles are scoped to the component.
// MyComponent.jsx
import React from 'react';
import styles from './MyComponent.module.css';
const MyComponent = () => {
return (
<div className={styles.container}>
Content goes here.
</div>
);
};
export default MyComponent;
/* MyComponent.module.css */
.container {
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
}
5. Styled Components:
Styled Components is a popular library that allows you to write CSS directly
within your JavaScript files using tagged template literals.
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
`;
const MyComponent = () => {
return (
<Container>
Content goes here.
</Container>
);
};
export default MyComponent;
Choose the method that best fits your project's requirements and your personal
or team preferences. Each approach has its own advantages and use cases.
*********************************************************************
3. What is Hot Module Replacement?
 Hot Module Replacement (HMR) is a feature in modern web development
environments that allows developers to update the application modules in real-
time without requiring a full page refresh. It's a powerful tool that enhances the
development experience by preserving the application state and speeding up the
development workflow.
 Here's how Hot Module Replacement typically works:
 Module Replacement: When a developer makes changes to a module (e.g., a
JavaScript file, stylesheet, or even a component in a framework like React or
Vue), the HMR system detects these changes.
 Dynamic Update: Instead of refreshing the entire page, HMR dynamically
updates the affected modules in the running application without losing the
current state. This includes applying changes to the UI, styles, and business
logic.
 Preserving State: HMR is designed to preserve the application state during
module updates. This means that if you are working on a specific part of your
application and make changes, you won't lose the current state of that part
when the module is updated.
 Faster Development: HMR significantly speeds up the development process by
eliminating the need for manual page refreshes. Developers can see the changes
instantly, making the development cycle more efficient.
 Error Handling: If there are errors in the updated module, HMR provides
meaningful feedback in the browser console. This helps developers identify
and fix issues quickly without needing to navigate through the entire
application.
 Hot Module Replacement is commonly used in conjunction with module
bundlers like Webpack and tools like React Hot Loader or Vue Loader. It's
widely supported in many modern JavaScript frameworks and build tools,
making it an essential feature for a smooth and productive development
experience.
*********************************************************************
4. What is the use of Parcel, Vite, Webpack?
 Parcel, Vite, and Webpack are all module bundlers and build tools commonly
used in modern web development. Each tool serves a similar purpose but may
have different focuses, use cases, and performance characteristics.
Parcel:
Focus:
 Simplicity and zero configuration.
Use Case:
 Quick setup and easy development experience without the need for
extensive configuration. Suitable for small to medium-sized projects.
Features:
 Requires minimal to no configuration.
 Supports various languages and file types out of the box.
 Provides automatic code splitting and caching for efficient builds.
 Built-in support for hot module replacement (HMR).
 Good for rapid prototyping and beginners.
Vite:
Focus:
 Fast development server and efficient bundling.
Use Case:
 Optimized for large-scale projects with a focus on fast development and
production builds. Particularly well-suited for modern frameworks like
Vue.js.
Features:
 Extremely fast development server with instant server start.
 Dynamic module system that loads only the modules needed for a
specific page.
 Supports HMR for rapid development.
 Uses native ES modules during development for faster browser loading.
 Optimized build for production with minimal bundle sizes.
Webpack:
Focus:
 Flexibility and extensive configuration options.
Use Case:
 Versatile and widely used for projects of any size, from small websites
to large-scale applications. Suitable for developers who need fine-
grained control over the build process.
Features:
 Highly configurable with a wide range of plugins and loaders.
 Supports code splitting, bundling, and tree-shaking for optimized
production builds.
 Widely adopted and has a large ecosystem of plugins.
 Integrates seamlessly with various front-end frameworks and tools.
 Supports HMR and provides powerful customization options.
 Choosing between Parcel, Vite, and Webpack depends on your specific project
requirements, development preferences, and the level of configuration control
you need. If you prefer simplicity and quick setup, Parcel might be a good fit.
For fast development and optimized production builds, Vite is a strong
contender. Webpack, with its extensive configurability, is a solid choice for
projects with complex requirements and a need for customization.
*********************************************************************
5. How does create-react-app work?
 create-react-app is a command-line tool provided by Facebook to set up a new
React project with a sensible default configuration, build scripts, and
development environment. It abstracts away the complexities of configuring
tools like Webpack and Babel, allowing developers to focus on building React
applications without dealing with the configuration hassle.
Here's a simplified overview of how create-react-app works:
Installation:
Install create-react-app globally using npm (Node Package Manager):
Command : npx create-react-app my-react-app
Project Initialization:
The create-react-app command initializes a new React project in the specified
directory (my-react-app in this case).
It sets up the project structure, including files like package.json,
public/index.html, and src/index.js.
Dependencies Installation:
create-react-app installs the necessary dependencies for building and running a
React application. These dependencies include tools like Webpack, Babel, and
development servers.
Default Configuration:
The tool comes with a pre-configured setup for Webpack, Babel, ESLint, and
other build tools. The configuration is hidden from the developer, allowing
them to get started quickly without worrying about the setup details.
Development Server:
create-react-app includes a development server that supports hot-reloading. As
you make changes to your code, the server automatically reloads the
application in the browser.
Scripts:
The package.json file includes predefined scripts for common tasks like
starting the development server (npm start), building the production-ready
bundle (npm run build), and running tests (npm test).
Zero Configuration:
Developers can start building their React application immediately without the
need to configure build tools. The tool abstracts away the complexity of setting
up and maintaining configurations.
Ejecting (Optional):
If developers need more control over the configuration, they have the option to
"eject" from create-react-app. Ejecting exposes the configuration files, allowing
for manual adjustments, but it also comes with the responsibility of maintaining
these configurations.
Overall, create-react-app simplifies the process of starting a new React project,
making it accessible to developers with varying levels of experience. It
promotes best practices and provides a solid foundation for building React
applications.
*********************************************************************
6. What is tree Shaking?
 Tree shaking is a technique used in JavaScript build processes, particularly in
the context of bundlers like Webpack, to eliminate dead (unused or
unreachable) code from the final bundled output. The goal is to reduce the size
of the bundle that is delivered to the browser, improving loading times and
overall performance.
The term "tree shaking" originates from the idea of shaking a tree to make the
dead leaves fall, leaving only the live ones. In the context of JavaScript, it
refers to removing the unnecessary or unused code during the build process.
Here's how tree shaking typically works:
ES6 Modules:
Tree shaking is most effective with ECMAScript 6 (ES6) modules, which have
a static structure that allows for the analysis of dependencies during the build
process.
Unused Code Detection:
Tree shaking tools analyze the dependency tree of the application to determine
which modules and exports are actually used by the application.
Elimination of Unused Code:
Code that is identified as unused or unreachable is removed from the final
bundled output. This includes functions, variables, or entire modules that are
not referenced.
Minification and Optimization:
After tree shaking, the resulting bundle is typically further optimized through
techniques like minification and compression to reduce its size even more.
Here's an example to illustrate tree shaking:
// module.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// app.js
import { add } from './module';
const result = add(5, 3);
console.log(result);
In this example, if the subtract function from module.js is not used in app.js,
the tree shaking process will eliminate the subtract function from the final
bundle.
To enable tree shaking, it's important to use tools like Webpack along with a
module system that supports static analysis, such as ES6 modules.
Additionally, dependencies in your package.json should be ES6 module-
compatible, and you should configure your bundler appropriately to take
advantage of tree shaking capabilities.
*********************************************************************
7. Diff between dependency and devDecpendency?
 In the context of a Node.js project and its package.json file, dependencies and
devDependencies serve different purposes:
Dependencies:
Role:
 Dependencies are packages that your project needs to run in a
production environment.
Installation:
 When users install your package or project, dependencies are installed
by default.
Examples: Express, React, lodash, axios, etc.
Command to Install:
npm install <package-name> or npm install (to install all dependencies).
DevDependencies:
Role:
 DevDependencies are packages that are only needed during
development or for building/testing purposes.
Installation:
 DevDependencies are not installed by default when users install your
package. They are typically used for tools, testing libraries, or build-
related dependencies.
Examples: Jest, Babel, ESLint, Webpack, testing libraries, etc.
Command to Install:
npm install <package-name> --save-dev or npm install -D <package-
name> or npm install --save-dev (to install all devDependencies).
Usage Scenario:
Dependencies Usage:
Required for the application to function properly in a production environment.
Included in the final build that users deploy.
Examples include the core libraries and frameworks your application relies on.
DevDependencies Usage:
Used for development, testing, and build processes.
Not included in the final production build.
Examples include testing libraries, transpilers, bundlers, linters, etc.
Example package.json:
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"express": "^4.17.1",
"axios": "^0.21.1"
},
"devDependencies": {
"jest": "^26.6.3",
"babel-core": "^6.26.3",
"eslint": "^7.22.0"
}
}
In this example:
express and axios are dependencies necessary for the application to run.
jest, babel-core, and eslint are devDependencies used during development,
testing, or build processes.
When someone installs this project using npm install, only the dependencies
will be installed by default. To also install devDependencies, they would need
to use npm install --dev or npm install -D. When deploying the project, only the
dependencies are typically required, and devDependencies can be omitted to
reduce the size of the deployment.
*********************************************************************
8. What is npm and npx?
 npm (Node Package Manager):
npm is the default package manager for Node.js, and it is used for managing
and distributing Node.js packages. It allows developers to easily install, share,
and manage dependencies for their projects. With npm, you can install
packages, manage project dependencies, and run scripts defined in your
project's package.json file.
Some common npm commands include:
Installing Dependencies:
 npm install
Installing a Specific Package:
 npm install <package-name>
Installing a Package Globally:
 npm install -g <package-name>
Running Scripts:
 npm run <script-name>
Viewing Installed Packages:
 npm list
Updating Packages:
 npm update
 npx:
npx is a tool that comes with npm (version 5.2.0 and higher) and is used to
execute Node.js packages. It allows you to run binaries from Node modules as
if they were installed globally, without actually installing them globally.
Some common npx use cases include:
Running a Package without Installing It:
 npx <package-name>
Executing a Binary from a Specific Version of a Package:
 npx -p <package-name>@<version> <command>
Running a One-off Command with a Temporary Package:
 npx create-react-app my-react-app
Executing a Local Binary:
 npx ./scripts/my-script.js
npx is particularly useful for running packages temporarily without polluting
the global package space. It ensures that you're running the latest version of a
package without the need for a global installation.
*********************************************************************
9. Diff between package.json and package-lock.json?
 package.json:
Role:
 package.json is a file in a Node.js project that contains metadata about
the project and configuration details, including project dependencies.
Contents:
 It includes information such as the project name, version, entry point
file, scripts, dependencies, and devDependencies.
Usage:
 Developers and tools use the package.json file to understand the
project's structure, dependencies, and scripts.
Changes:
 Developers manually modify the package.json file to add or update
dependencies, scripts, or other project details.
Commit to Version Control:
 The package.json file is typically committed to version control systems
like Git.
package-lock.json:
Role:
 package-lock.json is a file generated by npm that provides a detailed,
version-specific description of the project's dependency tree.
Contents:
 It includes information about each package, its version, and a resolved
URL or path. This file helps ensure consistency in dependency versions
across different installations.
Usage:
 It is used by npm to guarantee that the same versions of dependencies
are installed on all machines. It also helps in creating a deterministic and
reproducible build environment.
Changes:
 The package-lock.json file is automatically generated and updated by
npm when dependencies are added or modified.
Commit to Version Control:
 It is recommended to commit the package-lock.json file to version
control to achieve consistency in dependency versions across
development, testing, and production environments.
Relationship:
 package.json defines project metadata, dependencies, and scripts.
 package-lock.json is generated based on the dependencies listed in
package.json and provides a snapshot of the dependency tree with specific
version details.
When to Commit:
 Both package.json and package-lock.json should generally be committed to
version control. This ensures that the entire development team, as well as
continuous integration and deployment systems, use the same dependency
versions.
 Committing these files helps in creating reproducible builds and avoiding
unexpected issues due to differences in dependency versions.
 In summary, package.json is the primary configuration file, while package-
lock.json is a lock file that ensures dependency versions are consistent across
different installations of the project. Both files play a crucial role in managing
and maintaining dependencies in Node.js projects.
*********************************************************************
10. Diff between console.log(<HeaderComponent/>) &
console.log(HeaderComponent())
 The difference between console.log(<HeaderComponent/>) and
console.log(HeaderComponent()) lies in how React components are rendered
and what each expression represents.
 console.log(<HeaderComponent/>):
This logs the JSX representation of the HeaderComponent to the console.
It does not actually render the component; instead, it logs the JSX code that
represents the component.
Example:
const HeaderComponent = () => <header>This is a Header</header>;
console.log(<HeaderComponent/>);
// Output: <header>This is a Header</header>
In this case, the output in the console is the JSX representation of the
HeaderComponent.
 console.log(HeaderComponent()):
This logs the result of calling the HeaderComponent function to the console.
It renders the HeaderComponent and logs the result.
Example:
const HeaderComponent = () => <header>This is a Header</header>;
console.log(HeaderComponent());
// Output: <header>This is a Header</header>
In this case, the output in the console is the actual rendered content of the
HeaderComponent.
In summary:
console.log(<HeaderComponent/>): Logs the JSX representation of the
component.
console.log(HeaderComponent()): Logs the rendered content of the
component.
It's important to note that in a React application, components are typically
rendered within the context of the application itself, not logged to the console.
The examples provided are for illustrative purposes and may not represent
common practices in React development.
*********************************************************************
11. What is React.Fragment?
 React.Fragment is a wrapper component in React that does not create an
additional DOM element. It is a way to group multiple children without
adding extra nodes to the DOM structure. The primary purpose of
React.Fragment is to avoid unnecessary div wrappers around elements
when you don't want to introduce additional nodes in the rendered output.
Before the introduction of React.Fragment, developers often used <div>
elements to wrap multiple components or elements, even when those divs were
not semantically meaningful. This practice could lead to unnecessary HTML
elements in the DOM, affecting the structure and styling of the page.
With React.Fragment, you can group elements without introducing an extra
node. It can be used in two ways:
1. Short Syntax:
import React from 'react';
const MyComponent = () => {
return (
<>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</>
);
};
2. Long Syntax:
import React from 'react';
const MyComponent = () => {
return (
<React.Fragment>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</React.Fragment>
);
};
Both examples are equivalent. The short syntax (<> ... </>) is often used for
brevity, especially when there is no need to include additional props on the
fragment.
Using React.Fragment is particularly useful in scenarios where you want to
group elements together but don't want to affect the structure of the rendered
output. It helps maintain clean and semantically meaningful HTML while
avoiding unnecessary divs or other container elements.
*********************************************************************
12. What is the purpose of dependency array in useEffect? What is the
difference when it is used and when it is not used?
 In React, the useEffect hook is used for handling side effects in functional
components. The dependency array in useEffect is an optional second
argument that determines when the effect should run. It consists of variables or
values that the effect depends on.
Purpose of the Dependency Array:
Without Dependency Array:
 If you omit the dependency array (useEffect(callback)), the effect will
run after every render, including the initial render.
 This can lead to unintended behaviors, especially if the effect interacts
with the component state or props, potentially causing infinite loops.
useEffect(() => {
// This effect runs after every render (including the initial render)
console.log('Effect ran');
});
With Dependency Array:
 When you provide a dependency array (useEffect(callback,
dependencies)), the effect will only run if any of the dependencies have
changed between renders.
 It helps control when the effect should be executed, making it more
efficient and avoiding unnecessary computations.
const MyComponent = ({ data }) => {
useEffect(() => {
// This effect runs only when the 'data' prop changes
console.log('Effect ran due to data change');
}, [data]);

return <div>{/* Component JSX */}</div>;


};
Difference:
Without Dependency Array:
 Runs after every render, including the initial render.
 No control over when the effect should run based on changes to specific
variables.
 Can lead to performance issues and unexpected behavior if not used
carefully.
With Dependency Array:
 Runs only when the specified dependencies change between renders.
 Provides control over when the effect should run, making it more
predictable and efficient.
 Helps avoid unnecessary computations and potential side effects.
const MyComponent = ({ count }) => {
// Without dependency array
useEffect(() => {
console.log('Effect ran without dependencies');
});
// With dependency array
useEffect(() => {
console.log('Effect ran with count as a dependency');
}, [count]);

return <div>{/* Component JSX */}</div>;


};
In the example above, the first useEffect without a dependency array will run
after every render, while the second useEffect with the dependency array will
only run if the count prop changes between renders. Using the dependency
array helps optimize the performance of your components and avoids
unnecessary computations.
*********************************************************************
13. What if 2 components are given will the state change in one component will
affect the other component’s state(child)?
 In React, state is typically local to a component, and changing the state in one
component does not automatically affect the state of another component, even
if one component is a child of the other.
If you have two components, one being a parent and the other being a child,
and you want to share state between them, you would need to lift the state up to
a common ancestor (a higher-level component) and then pass down the state
and any necessary functions as props.
Here's a basic example:
import React, { useState } from 'react';
// Child component
const ChildComponent = ({ childState, setChildState }) => {
return (
<div>
<p>Child State: {childState}</p>
<button onClick={() => setChildState(childState + 1)}>Increment
Child State</button>
</div>
);
};
// Parent component
const ParentComponent = () => {
const [parentState, setParentState] = useState(0);
return (
<div>
<p>Parent State: {parentState}</p>
<button onClick={() => setParentState(parentState + 1)}>Increment
Parent State</button>
<ChildComponent childState={parentState}
setChildState={setParentState} />
</div>
);
};
export default ParentComponent;
In this example:
 The ParentComponent maintains the state (parentState) and provides a way to
update it.
 The ChildComponent receives the state as a prop (childState) and a function to
update the state (setChildState). It doesn't have direct access to modify the
parentState but can update it indirectly through the passed-down function.
 This way, when the state is updated in the ParentComponent, the new state is
passed down to the ChildComponent, and any updates to the state in the child
are done through the function provided by the parent.
 If you need to manage state that is shared among multiple components at
different levels in the component tree, you might want to explore state
management solutions like Context API or a state management library (e.g.,
Redux).
*********************************************************************
14.What is the use of return in useEffect?
 In the useEffect hook in React, the return statement is used to define a cleanup
function. This cleanup function is executed when the component is unmounted
or when the dependencies of the useEffect change, causing it to run again.
The useEffect hook allows you to perform side effects in your functional
components. These side effects can include data fetching, subscriptions, or
manually changing the DOM, among other things. The cleanup function is a
way to perform any necessary cleanup or resource cleanup when the
component is about to be removed from the DOM or when the dependencies
change.
Here is an example:
import React, { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
// This code runs when the component mounts

// Cleanup function
return () => {
// This code runs when the component is unmounted or when the
dependencies change
console.log('Cleanup function executed');
};
}, []); // Dependency array is empty, so it only runs on mount and
unmount

return <div>{/* Component JSX */}</div>;


};
export default MyComponent;
In this example:
The code inside the useEffect block runs when the component mounts.
The cleanup function inside the return statement runs when the component is
unmounted or when the dependencies change (in this case, there are no
dependencies, so it only runs on mount and unmount).
Common use cases for cleanup functions include:
Clearing up subscriptions:
 If you subscribe to an external data source or event within the useEffect,
the cleanup function is where you would unsubscribe to avoid memory
leaks.
Clearing up timers or intervals:
 If you set up timers or intervals in the useEffect, the cleanup function is
where you would clear or cancel them.
Cleaning up resources:
 If your effect involves manually changing the DOM or allocating
resources, you can use the cleanup function to release or clean up those
resources.
 By using the return statement in useEffect, you ensure that your
component is well-maintained and avoids potential memory leaks or
unexpected behavior.
*********************************************************************
15. Diff b/w client-side routings and server-side routing?
 Client-side routing and server-side routing refer to different approaches for
handling navigation and rendering content in web applications. Let's explore
the key differences between them:
Client-Side Routing:
Navigation Handling:
In the Browser:
 Client-side routing is handled within the browser using JavaScript.
No Page Reload:
 When a user clicks on a link or changes the URL, JavaScript updates the
DOM dynamically without causing a full page reload.
Rendering Content:
Single-Page Applications (SPAs):
 Client-side routing is commonly associated with SPAs where a single
HTML page is loaded initially, and subsequent navigation is handled by
updating the content dynamically.
User Experience:
Faster Transitions:
 Client-side routing often provides smoother transitions between pages as
only the content that changes is loaded.
More Responsive:
 The application can feel more responsive as it doesn't need to make
round-trips to the server for every navigation.
Frameworks and Libraries:
Popular Frameworks:
 React, Angular, Vue, and other modern frontend frameworks often use
client-side routing for building SPAs.
Search Engine Optimization (SEO):
Initial Challenge:
 Client-side routing can pose challenges for SEO as search engines
historically struggled with indexing content dynamically loaded via
JavaScript.
Solutions Exist:
 Techniques such as server-side rendering (SSR) or pre-rendering can be
employed to address SEO concerns.
Server-Side Routing:
Navigation Handling:
Handled by Server:
 Server-side routing is managed by the web server itself.
Page Reloads:
 Clicking on a link or changing the URL typically results in a full page
reload, and the server sends back the HTML for the new page.
Rendering Content:
Multiple HTML Pages:
 Each distinct page corresponds to a separate HTML file on the server.
Traditional Web Apps:
 Traditional multi-page applications often use server-side routing.
User Experience:
Slower Transitions:
 Page transitions may be slower compared to client-side routing, as the
browser needs to fetch and load a new HTML page from the server.
Frameworks and Technologies:
Express, Django, Ruby on Rails:
 Server-side frameworks like Express.js (Node.js), Django (Python), and
Ruby on Rails (Ruby) commonly use server-side routing.
Search Engine Optimization (SEO):
Naturally SEO-Friendly:
 Server-side routing is naturally SEO-friendly as each page has its own
URL and content is directly present in the HTML delivered by the
server.
Hybrid Approaches:
Next.js (React):
 Next.js is a framework for React that allows developers to use both
server-side rendering (SSR) and client-side rendering (CSR) based on
the specific needs of the application.
Nuxt.js (Vue):
 Nuxt.js is a similar framework for Vue.js, providing options for server-
side rendering, client-side rendering, or a combination of both.
 In summary, client-side routing and server-side routing offer different trade-
offs in terms of user experience, performance, and SEO. The choice between
them often depends on the nature of the application, the desired user
experience, and the technologies/frameworks being used. Many modern web
applications utilize a combination of both client-side and server-side rendering
for optimal performance and SEO.
*********************************************************************
16. Explain the concept of code splitting and its benefits in React?
 Code splitting is a technique used to improve the performance of web
applications by splitting the application code into smaller and more manageable
chunks. Instead of loading the entire application code at once, code splitting
allows you to load only the necessary parts of the code when they are needed.
In React, code splitting is often achieved through dynamic imports or using
tools like Webpack with its built-in support for code splitting. Here's an
explanation of the concept and its benefits:
Concept of Code Splitting:
Dynamic Imports:
 Code splitting involves using dynamic imports to load modules or
components asynchronously at runtime, rather than including them in
the main bundle.
 Dynamic imports return a Promise, and the imported module is loaded
only when the Promise is resolved.
Breaking the Bundle:
 Instead of having a single large JavaScript bundle that contains the
entire application, code splitting breaks the bundle into smaller chunks.
 Each chunk represents a separate module or a group of related modules.
On-Demand Loading:
 Code is loaded on-demand, meaning that chunks are fetched and
executed only when a particular feature or route is accessed by the user.
 This helps reduce the initial loading time of the application.
Benefits of Code Splitting in React:
Faster Initial Load:
 By loading only the essential code needed for the initial view, the
application starts up faster.
 Users see a quicker initial render, enhancing the perceived performance.
Reduced Bandwidth Usage:
 Smaller initial bundles mean reduced bandwidth usage, especially for
users on slower networks or mobile devices.
 Users download only the code necessary for the current view, saving
bandwidth.
Improved Caching:
 Smaller, more granular chunks of code are easier to cache. Cached
chunks can be reused across different views or user sessions.
 This optimizes subsequent visits to the application by loading cached
code.
Optimized for Different Devices:
 Code splitting allows you to optimize your application for different
devices by loading only the code necessary for the specific device or
screen size.
 This is particularly beneficial for mobile users with limited resources.
Enhanced Developer Experience:
 Code splitting makes it easier to manage and maintain large codebases
by breaking them into smaller, more focused modules.
 Developers can work on isolated parts of the application without
affecting the entire codebase.
Implementation in React:
// Using React.lazy for component-based code splitting
const MyComponent = React.lazy(() => import('./MyComponent'));
// Usage in a component
const App = () => (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
</div>
);
 In this example, React.lazy is used to lazily load the MyComponent module
when it is first rendered. The Suspense component is used to specify a fallback
UI while the component is being loaded.
 By leveraging code splitting in React, developers can significantly improve the
performance and user experience of their applications, especially for larger and
more complex projects.
*********************************************************************
17. How does react handle routing and navigation?
 React itself doesn't provide built-in support for routing and navigation in web
applications. However, there are several popular third-party libraries that
developers commonly use to handle routing and navigation in React
applications. Two of the most widely used libraries for this purpose are React
Router and Reach Router. I'll provide an overview of React Router, as it is the
more commonly used library.
React Router:
React Router is a declarative routing library for React applications. It allows
developers to define how different components should be displayed based on
the current URL. React Router provides a set of components that enable
navigation and rendering of components based on the URL.
Here are the key concepts in React Router:
<BrowserRouter> and <HashRouter>:
 The <BrowserRouter> and <HashRouter> components provide the
foundation for routing.
 <BrowserRouter> uses the HTML5 history API for cleaner URLs
(e.g., /about), while <HashRouter> uses the hash portion of the URL
(e.g., /#/about).
<Route>:
 The <Route> component is used to define a route and specify which
component should be rendered when the route matches the current URL.
 It is typically used within the <BrowserRouter> or <HashRouter>.
<Link> and NavLink:
 The <Link> component is used to create links between different routes.
 NavLink is a specialized version of <Link> that can style the link based
on whether its route is active.
Nested Routes:
 React Router supports nested routes, allowing the rendering of
components within other components based on the URL hierarchy.
Programmatic Navigation:
 React Router provides a history object that allows for programmatic
navigation, such as navigating to a different route based on user actions
or events.
Example Usage:
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-
router-dom';
const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;
const Contact = () => <h2>Contact</h2>;
const App = () => {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<hr />
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
};
export default App;
In this example:
 The <Router> component is used to wrap the entire application.
 <Link> components create navigation links.
 <Route> components define the mapping between routes and components to
render.
Additional Libraries:
React Router Dom:
 The react-router-dom package provides the core components for web
applications. It includes components like BrowserRouter, Route, Link,
etc.
React Router Native:
 For React Native applications, you can use the react-router-native
package.
 React Router is a powerful and flexible library for handling navigation in React
applications, and it is widely adopted in the React ecosystem. It provides a
declarative and component-based approach to building navigation in your
applications.
*********************************************************************
18. What is Higher Order Component (HOC) in react?
 A Higher Order Component (HOC) in React is a pattern that involves
wrapping a component with another component to enhance or modify its
behavior. It's a function that takes a component and returns a new
component with additional functionality. HOCs are a way to reuse
component logic and share it between different parts of an application.
Here's a general structure of a Higher Order Component:
const higherOrderComponent = (WrappedComponent) => {
class HOC extends React.Component {
// Additional logic or state can be implemented here
render() {
// Render the wrapped component with additional props or
behavior
return <WrappedComponent {...this.props} />;
}
}
return HOC;
};
Key characteristics and use cases of Higher Order Components:
Reusability:
 HOCs promote code reuse by encapsulating common functionality in a
separate component.
 The same HOC can be applied to multiple components to share the same
behavior.
Props Manipulation:
 HOCs can manipulate the props passed to the wrapped component by
adding, modifying, or removing props based on certain conditions.
State Management:
 HOCs can manage state or provide additional state to the wrapped
component.
 This is useful for cases where multiple components need to share the
same state logic.
Conditional Rendering:
 HOCs can conditionally render the wrapped component based on certain
conditions, such as authentication status, user roles, or other application
state.
Lifecycle Methods:
 HOCs can intercept and modify lifecycle methods of the wrapped
component.
 This is useful for tasks like fetching data before rendering or cleaning up
resources on unmount.
Example:
Let's create a simple HOC that adds a isAdmin prop to a component based
on a user's role:
const withAdminStatus = (WrappedComponent) => {
class WithAdminStatus extends React.Component {
render() {
// Simulate checking user's role and adding 'isAdmin' prop
const isAdmin = true; // Replace with actual logic
// Return the wrapped component with additional 'isAdmin' prop
return <WrappedComponent {...this.props} isAdmin={isAdmin}
/>;
}
}
return WithAdminStatus;
};
// Usage of the HOC
const UserProfile = ({ isAdmin }) => (
<div>
<p>User Profile</p>
{isAdmin && <p>Admin Privileges</p>}
</div>
);
const UserProfileWithAdminStatus =
withAdminStatus(UserProfile);
// Render the component with added isAdmin prop
ReactDOM.render(<UserProfileWithAdminStatus />,
document.getElementById('root'));
 In this example, the withAdminStatus HOC adds an isAdmin prop to the
UserProfile component. The wrapped component (UserProfile) can then
conditionally render content based on the added prop.
 Keep in mind that with the introduction of React Hooks, many patterns that
previously required HOCs can now be achieved using custom hooks and the
useEffect or useState hooks. HOCs are still relevant in certain scenarios, but
hooks provide a more concise and flexible approach in many cases.
*********************************************************************
19. What is controlled and Uncontrolled component in react? Or How we can
handle forms input values?
 We have 2 ways to handle the input value, the first one is the Controlled
Component and the second is Uncontrolled component
Ok, then what is the difference?
Let’s Start with the controlled component!
The controlled component is a way that you can handle the form input value
using the state and to change the input value there is only one way to change it
is using setState or useState if you are using React Hooks and you can change
this state using one of the events like onChange and when the user starts
writing any character setState or useState will be called and update the state of
this input then it will add the new value inside the input.

Example using react hooks (useState):


import React, { useState } from "react";

export default function App() {


const [inputValue, setInputValue] = useState("");
const handleInputChange = (e) => {
setInputValue(e.target.value)
}
const handleSubmitButton = () => {
alert(inputValue);
};
return (
<div className="App">
<input value={inputValue} onChange={handleInputChange} />
<input type="submit" value="submit" onClick={handleSubmitButton} />
</div>
);
}

in the above example, we use the controlled component to handle the form
input value using React Hooks and every time you will type a new character,
handleInputChange is called and it takes in the new value of the input and sets
it in the state then you can use this value and print it inside alert when
submitting use handleSubmitButton.

Now, let’s talk about Uncontrolled Components!


The uncontrolled component is like traditional HTML form inputs that you will
not be able to handle the value by yourself but the DOM will take care of
handling the value of the input and save it then you can get this value using
React Ref and for example, print it inside alert when submitting or play with
this value as you want.

Example using react hooks (useRef):


import React, { useRef } from "react";

export default function App() {


const inputRef = useRef(null);
const handleSubmitButton = () => {
alert(inputRef.current.value);
};
return (
<div className="App">
<input type="text" ref={inputRef} />
<input type="submit" value="submit" onClick={handleSubmitButton} />
</div>
);
}
Now you know what is the difference between the controlled component and
the uncontrolled component

Maybe now the question that comes to your mind is when should I use the
controlled component and when should I use the uncontrolled component?
Ok basically it’s up to you and up to your use case so for example

You can use the controlled component when you create


Form validation so you always need to know the value of the input when typing
to check if it’s a valid character or not!
Disable the submit button unless all fields have valid data
If you have a specific format like the credit card input
But if you don’t need any of that and think that the uncontrolled will be simpler
for you, go for it.

Additional info
You can use Uncontrolled component to handle the form validation when
typing but without update the input value with the state like the controlled but
you can use setState or useState inside handle change to update the state then
you can check this state if it’s valid or not and display an error message if it’s
not valid but don’t use the state value inside the input value
*********************************************************************
20. Explain the concept of reconciliation in React?
 Reconciliation :
React compares the Virtual DOM with Real DOM. It finds out the changed
nodes and updates only the changed nodes in Real DOM leaving the rest nodes
as it is. This process is called Reconciliation.

Generic Reconciliation methods have complexity of O(n3) . Normally we have


thousands of nodes in any application. This will be too expensive to use generic
methods.
React implements a heuristic O(n) algorithm based on two assumptions:
Two elements of different types will produce different trees.
The developer can hint at which child elements may be stable across different
renders with a key prop.
In practice, these assumptions are valid for almost all practical use cases.
Diffing Algorithm
React first compares the two root elements. The behavior is different depending
on the types of the root elements.
React compared the root DOM Elements Types.
Elements of different types: Whenever the root elements have different types,
React will tear down the old tree and build the new tree from scratch. Going
from <a> to <img>, or from <Article> to <Comment>, or from <Button> to
<div> — any of those will lead to a full rebuild. This will lead to component
unmount and mount lifecycle calls too.
DOM Elements Of The Same Type: When comparing two React DOM
elements of the same type, React looks at the attributes of both, keeps the same
underlying DOM node, and only updates the changed attributes. After handling
the DOM node, React then recurses on the children. This will lead to
component update lifecycle calls.
Why key should be used in lists?
By default, when recursing on the children of a DOM node, React just iterates
over both lists of children at the same time and generates a mutation whenever
there’s a difference.
Old
<ul>
<li>first</li>
<li>second</li>
</ul>
New
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
Here React will add a third element directly. But if the order changes then react
gets confused in comparing. To overcome this key is introduced.
<ul>
<li key=”2015">Duke</li>
<li key=”2016">Villanova</li>
</ul>
Updated list.
<ul>
<li key=”2014">Connecticut</li>
<li key=”2015">Duke</li>
<li key=”2016">Villanova</li>
</ul>
Here react will identify the component with key and update only the changed
items.
Keys should be stable, predictable, and unique. Unstable keys (like those produced
by Math.random()) will cause many component instances and DOM nodes to be
unnecessarily recreated, which can cause performance degradation and lost state in
child components.
We don’t recommend using indexes for keys if the order of items may change.
This can negatively impact performance and may cause issues with component
state.
*********************************************************************
21. How can we fetch API data without using useEffect hook?
 While the useEffect hook is commonly used for making API requests in React
functional components, you can also fetch API data without using useEffect.
Here are a few alternative approaches:
1. Fetch in Function Body:
import React, { useState } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the fetchData function wherever needed, e.g., in an event
handler or during component rendering
// fetchData();
return (
<div>
{/* Render the data */}
{data && <p>{data.message}</p>}
</div>
);
};
export default MyComponent;
In this example, the fetchData function is defined within the component body,
and you can call it wherever needed, such as in an event handler or during the
rendering process. Note that calling fetchData directly in the render can lead to
multiple API requests depending on how often the component renders.
2. Fetch in Event Handlers:
import React, { useState } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
{/* Render the data */}
{data && <p>{data.message}</p>}
</div>
);
};
export default MyComponent;
In this example, the API request is triggered by a button click. The fetchData
function is called when the button is clicked, and the data is updated
accordingly.
While these approaches work, it's important to note that using useEffect is a
more conventional and recommended way to handle side effects, including API
requests, in React. The useEffect hook ensures that side effects are properly
managed in terms of component lifecycle and potential memory leaks.
*********************************************************************
22. What are the security measures which should be considered during
development?
 Securing a web application is a critical aspect of software development. Here
are some key security measures that should be considered during the
development process:
1. Data Validation:
 Validate and sanitize user input on both the client and server sides.
 Use input validation libraries or frameworks to prevent common
vulnerabilities like SQL injection and Cross-Site Scripting (XSS).
2. Authentication and Authorization:
 Implement strong user authentication mechanisms, such as password
hashing and salting.
 Use secure protocols like HTTPS to protect data during transmission.
 Enforce proper access controls and authorization policies to ensure users
have the necessary permissions.
3. Session Management:
 Use secure session management practices, including secure, random
session IDs and session timeouts.
 Store session data securely on the server side.
4. Cross-Site Request Forgery (CSRF) Protection:
 Implement CSRF tokens to protect against CSRF attacks.
 Validate and enforce the origin of incoming requests.
5. Cross-Site Scripting (XSS) Protection:
 Sanitize and escape user input to prevent XSS attacks.
 Use content security policies (CSP) to control the types of content that
can be loaded on a page.
6. Security Headers:
 Utilize security headers, such as Strict-Transport-Security, Content-
Security-Policy, and X-Content-Type-Options, to enhance the security
of web applications.
7. File Upload Security:
 Validate and restrict file uploads to prevent malicious uploads.
 Store uploaded files outside the web root and apply proper file type
validation.
8. API Security:
 Use API keys or tokens for authentication in APIs.
 Implement rate limiting and throttling to protect against abuse.
9. Error Handling:
 Customize error messages to avoid exposing sensitive information.
 Log errors securely and regularly monitor logs for suspicious activity.
10. Dependency Scanning:
 Regularly update and patch dependencies to address known
vulnerabilities.
 Use tools to scan and monitor dependencies for security issues.
11. Content Security:
 Sanitize and validate user-generated content to prevent content injection
attacks.
 Implement proper content validation and filtering.
12. Security Audits and Testing:
 Conduct regular security audits and code reviews.
 Perform security testing, including penetration testing and security
scanning.
13. Data Encryption:
 Encrypt sensitive data both at rest and during transit.
 Use strong encryption algorithms and protocols.
14. Monitoring and Incident Response:
 Implement real-time monitoring for security events.
 Have an incident response plan in place to quickly address and mitigate
security incidents.
15. Education and Training:
 Train developers, administrators, and users on security best practices.
 Foster a security-aware culture within the development team.
16. Compliance with Regulations:
 Ensure compliance with relevant regulations and standards (e.g., GDPR,
HIPAA) based on the nature of the application.
17. Security Patching:
 Regularly apply security patches for the underlying operating system,
web server, and other software components.
 Security is an ongoing process, and a proactive approach is essential to
identifying and addressing potential vulnerabilities. Adopting secure
coding practices, staying informed about the latest security threats, and
actively addressing security concerns throughout the development
lifecycle are crucial for building robust and secure web applications.
*********************************************************************
23. Can we setState inside a component without updating state?
 In React, when you call setState inside a component, it triggers a re-render of
the component with the updated state. The purpose of setState is to update the
component's state and, consequently, trigger a re-render to reflect the changes
in the user interface.
If you call setState without updating the state, React will still re-render the
component, but the state won't change. While technically possible, it's
generally not considered a good practice because it can lead to
unnecessary renders and might impact performance.
Here's an example demonstrating the scenario:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
// Calling setCount with the same state value (count) doesn't
change the state
setCount(count);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment Count</button>
</div>
);
};
export default MyComponent;
In this example, calling setCount(count) doesn't actually update the state
because it's setting the state to the same value. However, it still triggers a re-
render of the component.
While there might be rare cases where intentionally triggering a re-render
without updating the state makes sense, it's generally recommended to use
setState when you want to update the state and reflect those changes in the UI.
If you need to perform some action without triggering a re-render, you might
consider using a different approach, such as using a regular variable or
managing such behavior outside the component state.
*********************************************************************
24. Multiple useEffect in same component?
 Yes, you can use multiple useEffect hooks in the same React component. Each
useEffect is independent and can be used to manage different side effects or
handle different lifecycle events. This is a common pattern in React
applications where you need to perform multiple actions in response to
different changes or events.
Here's an example of a component with multiple useEffect hooks:
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
const [status, setStatus] = useState('Loading');
// useEffect for fetching data
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
setStatus('Loaded');
} catch (error) {
console.error('Error fetching data:', error);
setStatus('Error');
}
};
fetchData(); // Trigger the effect on mount
}, []); // Empty dependency array means this effect runs once on mount
// useEffect for additional side effect (e.g., logging)
useEffect(() => {
console.log('Component rendered or data updated:', data);
// Additional actions based on data or component rendering
}, [data]); // Dependency array with 'data' means this effect runs
whenever 'data' changes
return (
<div>
<p>Status: {status}</p>
{data && <p>Data: {data}</p>}
</div>
);
};
export default MyComponent;
In this example:
 The first useEffect is responsible for fetching data when the component
mounts. It runs once on mount due to the empty dependency array [].
 The second useEffect logs a message whenever the data state changes or the
component renders. It has a dependency array [data], so it runs whenever data
changes.
 Each useEffect runs independently and can have its own dependencies,
allowing you to organize your side effects based on different triggers or events.
This pattern helps keep the logic modular and easier to understand.
*********************************************************************
25. Higher order component or custom hooks?
 Both Higher Order Components (HOCs) and custom hooks are patterns in
React that offer a way to reuse and share component logic. The choice
between them depends on the specific use case, readability, and personal
or team preferences. Here are some considerations for each:
Higher Order Components (HOCs):
Composition:
 HOCs promote composition by wrapping a component with additional
behavior.
 They allow you to reuse logic across multiple components by applying
the HOC to different components.
Props Manipulation:
 HOCs can manipulate props before passing them to the wrapped
component, allowing for customization.
 They are suitable for scenarios where you want to inject additional props
or modify existing ones.
Lifecycle Methods:
 HOCs can intercept and modify lifecycle methods of the wrapped
component.
 Useful for tasks such as fetching data, managing subscriptions, or
cleaning up resources.
Cross-Cutting Concerns:
 Good for addressing cross-cutting concerns that affect multiple
components, such as authentication or logging.
Existing Codebases:
 HOCs are a common pattern in older React codebases and libraries.
Custom Hooks:
Logic Encapsulation:
 Custom hooks encapsulate reusable logic in a single function, promoting
a more modular approach.
 Hooks are suitable for extracting logic related to state, effects, or any
other aspect of a component.
Readability:
 Hooks improve readability by keeping related logic together in one
place.
 Especially helpful for extracting complex logic that may span multiple
lifecycle methods.
No Component Hierarchy Impact:
 Custom hooks don't affect the component hierarchy, making them more
flexible and easier to reason about.
 Suitable for scenarios where you want to share logic between
components without affecting their hierarchy.
Functional Programming:
 Aligns well with functional programming principles, allowing you to
create small, focused functions.
New React Patterns:
 Custom hooks are a newer pattern and align well with the functional
components and Hooks paradigm introduced in React.
Choosing Between HOCs and Custom Hooks:
Composition vs. Readability:
 If you prioritize composition and prop manipulation, HOCs might be
more suitable.
 If you prioritize encapsulation and readability, custom hooks might be
more appropriate.
Project Consistency:
 Consider the existing patterns in your project or team preferences. If
your team is already using a specific pattern consistently, it might make
sense to stick with it for consistency.
Nature of the Logic:
 Consider the nature of the logic you're extracting. If it's more about
props manipulation, lifecycle methods, or cross-cutting concerns, HOCs
might be a good fit. If it's more about encapsulating state and effects,
custom hooks could be a better choice.
 In many cases, custom hooks provide a more modern and concise way to share
and reuse logic. However, both HOCs and custom hooks have their places in
React development, and the choice depends on the specific requirements and
preferences of your project or team.
*********************************************************************
26. Explain Middleware in React which you have used?

In the context of React, middleware is often associated with state management
libraries like Redux. Middleware functions provide a way to intercept actions
before they reach the reducer, allowing you to apply additional logic or side
effects. While middleware is not a core concept of React itself, it is commonly
used with state management libraries to enhance and extend their functionality.
Example with Redux Middleware:
Redux middleware is used to perform tasks such as logging, making
asynchronous API calls, or handling side effects. The most commonly used
middleware for Redux is redux-thunk. Here's a brief example of using
middleware in a Redux setup:
Install Dependencies:
 npm install redux react-redux redux-thunk
Setup Redux with Middleware:
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
export default store;
Create a Thunk Action:
// actions.js
import axios from 'axios';
// Thunk action using Redux Thunk middleware
export const fetchData = () => async (dispatch) => {
try {
dispatch({ type: 'FETCH_DATA_REQUEST' });
const response = await axios.get('https://api.example.com/data');
dispatch({ type: 'FETCH_DATA_SUCCESS', payload:
response.data });
} catch (error) {
dispatch({ type: 'FETCH_DATA_FAILURE', payload:
error.message });
}
};
Dispatch Thunk Action from Component:
// MyComponent.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchData } from './actions';
const MyComponent = () => {
const dispatch = useDispatch();
const data = useSelector(state => state.data);
useEffect(() => {
// Dispatch the thunk action
dispatch(fetchData());
}, [dispatch]);
return (
<div>
{data.loading && <p>Loading...</p>}
{data.error && <p>Error: {data.error}</p>}
{data.data && <p>Data: {data.data}</p>}
</div>
);
};
export default MyComponent;
In this example:
The redux-thunk middleware allows you to dispatch asynchronous actions
(thunks) that can perform side effects, such as making API calls.
The fetchData thunk action is an asynchronous function that dispatches
multiple actions during its lifecycle: request, success, or failure.
The middleware intercepts the thunk action, allowing it to perform
asynchronous logic before reaching the reducer.
Middleware in Redux provides a powerful way to extend the functionality of
state management by introducing additional logic and side effects. Other
popular middleware for Redux includes redux-saga and redux-observable, each
with its own approach to handling asynchronous actions and side effects.
*********************************************************************
27. Explain service and web workers?
 Service Workers:
 A service worker is a script that runs in the background of a web
application, separate from the main thread, and provides features
like offline support, push notifications, and background
synchronization. It acts as a proxy between the web application and
the network, intercepting network requests, caching resources, and
enabling offline capabilities.
Key characteristics and use cases of service workers:
Offline Support:
 Service workers can cache resources, allowing a web application to
work offline by serving cached content when the network is unavailable.
Push Notifications:
 Service workers enable web applications to receive push notifications,
even when the application is not open in the browser.
Background Synchronization:
 Background sync allows web applications to perform tasks, such as
sending data to a server, even when the application is not actively
running.
Improved Performance:
 By caching resources and intercepting network requests, service workers
can significantly improve the performance of a web application.
Security:
 Service workers are served over HTTPS to ensure a secure connection.
Web Workers:
 Web workers are JavaScript scripts that run in the background,
separate from the main browser thread. They allow for parallel
execution of code, enabling developers to perform computationally
expensive tasks without blocking the user interface.
Key characteristics and use cases of web workers:
Parallel Execution:
 Web workers run in a separate thread, allowing them to execute code in
parallel with the main thread. This can improve performance for tasks
that are computationally intensive.
Non-Blocking:
 Web workers operate independently of the main thread, preventing long-
running tasks from blocking the user interface and maintaining a
responsive user experience.
Communication:
 Web workers communicate with the main thread using a messaging
system. They can send and receive messages, allowing for data
exchange between the main thread and the worker.
Background Processing:
 Useful for tasks such as data processing, image manipulation, or other
calculations that may take a considerable amount of time.
Dedicated and Shared Workers:
 There are two types of web workers: dedicated workers (associated with
a single script) and shared workers (shared among multiple scripts).
 In summary, service workers are primarily used for features related to offline
support, push notifications, and background synchronization in web
applications. On the other hand, web workers are used for parallelizing tasks
and performing background processing to enhance the overall performance and
responsiveness of a web application. Both service workers and web workers
contribute to building more robust and efficient web applications.
*********************************************************************
28. Explain Stateless component?
 In React, a stateless component, also known as a functional component, is a
type of component that doesn't have its own internal state. Stateless
components are defined as plain JavaScript functions and are primarily
responsible for rendering UI based on the props they receive. They are also
referred to as "dumb components" or "presentational components."
Here's an example of a stateless/functional component:
import React from 'react';
const Greeting = (props) => {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
};
export default Greeting;
Key characteristics of stateless components:
No Internal State:
 Stateless components do not manage their own state using setState.
They are entirely reliant on the props passed to them for data.
Functional Syntax:
 Stateless components are written as regular JavaScript functions, making
them concise and easy to understand.
Pure Rendering:
 Stateless components are considered pure components because their
output is solely determined by their input props. Given the same set of
props, a stateless component will always render the same output.
Focus on UI Rendering:
 Stateless components are primarily focused on rendering UI based on
the props they receive. They are often used for presentational purposes.
No Lifecycle Methods:
 Stateless components do not have access to lifecycle methods (e.g.,
componentDidMount, componentDidUpdate). If lifecycle methods or
local state management is required, a class component should be used.
Implicit Return:
 Stateless components often use the implicit return syntax of arrow
functions, where the return statement is omitted, and the result is
implicitly returned.
Usage example:
import React from 'react';
import Greeting from './Greeting';
const App = () => {
return (
<div>
<Greeting name="John" />
<Greeting name="Jane" />
</div>
);
};
export default App;
In this example, the Greeting component is a stateless component that receives
the name prop and renders a greeting message. Stateless components are useful
for encapsulating reusable UI elements and keeping the component tree simple
and focused.
*********************************************************************
29. How does you Fetch Multiple API at single time.
 To fetch data from multiple APIs simultaneously in a React application,
you can use asynchronous operations, such as Promise.all or async/await,
to handle multiple fetch requests concurrently. Here's an example using
the fetch API and async/await syntax:
Let's say you have two API endpoints you want to fetch data from:
const apiUrl1 = 'https://api.example.com/data1';
const apiUrl2 = 'https://api.example.com/data2';
Now, you can create an asynchronous function to fetch data from both APIs
simultaneously:
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [data1, setData1] = useState(null);
const [data2, setData2] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
// Use Promise.all to fetch data from multiple APIs concurrently
const [response1, response2] = await Promise.all([
fetch(apiUrl1),
fetch(apiUrl2),
]);
// Check if the responses are successful
if (!response1.ok || !response2.ok) {
throw new Error('Failed to fetch data');
}
// Parse the JSON data
const result1 = await response1.json();
const result2 = await response2.json();
// Update the state with the fetched data
setData1(result1);
setData2(result2);
} catch (error) {
console.error('Error fetching data:', error);
}
};
// Call the fetchData function
fetchData();
}, []); // Empty dependency array means this effect runs once on mount
return (
<div>
<h2>Data from API 1:</h2>
<pre>{JSON.stringify(data1, null, 2)}</pre>
<h2>Data from API 2:</h2>
<pre>{JSON.stringify(data2, null, 2)}</pre>
</div>
);
};
export default MyComponent;
In this example:
The fetchData function uses Promise.all to fetch data from both APIs
concurrently.
It then checks if the responses are successful and parses the JSON data.
The state is updated with the fetched data, and you can render or manipulate
the data as needed.
Note: Make sure to handle errors appropriately and consider loading states or
error messages based on the fetching status. Additionally, handle any CORS or
security-related issues when making cross-origin requests.
*********************************************************************
30. Interceptors in axios library?
 In Axios, interceptors are functions that you can define globally or on a per-
request basis to run your code or modify the request or response before the
request is sent or after the response is received. Axios provides request,
response, error, and config interceptors that allow you to globally intercept
requests and responses, and handle errors.
Here's an overview of how you can use interceptors in Axios:
1. Request Interceptors:
Request interceptors are functions that run before the request is sent. They can
be used to modify the request configuration or headers.
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
(config) => {
// Do something before the request is sent
console.log('Request Interceptor:', config);
return config;
},
(error) => {
// Do something with request error
return Promise.reject(error);
}
);
2. Response Interceptors:
Response interceptors run after the response is received but before it's passed to
the .then() or .catch() functions. They can be used to modify the response data
or handle errors.
import axios from 'axios';
// Add a response interceptor
axios.interceptors.response.use(
(response) => {
// Do something with the response data
console.log('Response Interceptor:', response);
return response;
},
(error) => {
// Do something with response error
return Promise.reject(error);
}
);
3. Error Interceptors:
Error interceptors run when there is an error during the request or response.
They can be used to handle or log errors.
import axios from 'axios';
// Add an error interceptor
axios.interceptors.response.use(
(response) => {
// Do something with the response data
return response;
},
(error) => {
// Do something with response error
console.error('Error Interceptor:', error);
return Promise.reject(error);
}
);
4. Config Interceptors:
Config interceptors are invoked when a request is created but before it is sent.
They can be used to modify the request configuration.
import axios from 'axios';
// Add a config interceptor
axios.interceptors.request.use(
(config) => {
// Do something with the request config
console.log('Config Interceptor:', config);
return config;
},
(error) => {
return Promise.reject(error);
}
);
Removing Interceptors:
To remove an interceptor, you can use the eject method. The interceptors object
returned by Axios contains request, response, and error keys.
const requestInterceptor = axios.interceptors.request.use((config)
=> {
// Do something with the request config
return config;
});
// Remove the request interceptor
axios.interceptors.request.eject(requestInterceptor);
Using interceptors in Axios allows you to centralize common logic, such as
adding authentication headers, handling loading states, or logging, making your
code more modular and maintainable.
*********************************************************************
31. React Suspense?
 React Suspense is a feature introduced in React to make it easier to work with
asynchronous code, especially when dealing with code-splitting and data
fetching. It allows components to "suspend" rendering while waiting for some
asynchronous operation to complete, such as fetching data from an API or
loading a dynamically imported module.
Key concepts and use cases of React Suspense:
Code-Splitting:
 React Suspense is often used in conjunction with code-splitting. Code-
splitting allows you to split your bundle into smaller chunks and load
them on demand.
Lazy Loading:
 The React.lazy function is used for lazy loading of components. It
allows you to load components only when they are actually needed.
 const MyLazyComponent = React.lazy(() =>
import('./MyComponent'));
<Suspense> Component:
 The <Suspense> component is used to wrap the part of your application
that may suspend. It takes a fallback prop, which specifies what to
render while waiting for the suspended content.
 <Suspense fallback={<LoadingSpinner />}>
<MyLazyComponent />
</Suspense>
Data Fetching:
 React Suspense can be used with data fetching libraries like Relay or the
experimental react-query to suspend rendering while waiting for data.
 const resource = fetchData(); // Fetch data using a data fetching
library
return (
<Suspense fallback={<LoadingSpinner />}>
<MyComponent data={resource} />
</Suspense>
);
Error Handling:
 React Suspense also supports error boundaries to gracefully handle
errors that occur during the suspended state.
const MyErrorBoundary = ({ error, resetErrorBoundary }) => (
<div>
<p>An error occurred: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);

return (
<ErrorBoundary FallbackComponent={MyErrorBoundary}>
<Suspense fallback={<LoadingSpinner />}>
<MyComponent />
</Suspense>
</ErrorBoundary>
);
 React Suspense simplifies the handling of asynchronous operations and
improves the user experience by allowing developers to declaratively specify
loading states and error boundaries. While it's a powerful feature, it's important
to note that not all libraries and components support React Suspense out of the
box, and its usage may depend on the specific requirements of your project.
Additionally, React Suspense is an evolving feature, and new improvements
may be introduced in future React releases.
*********************************************************************
32. How will you select b/w SSR and CSR for your application? What
parameters will you consider?
 The choice between Server-Side Rendering (SSR) and Client-Side Rendering
(CSR) for your application depends on various factors, and each approach has
its advantages and trade-offs. Here are some key parameters to consider when
making the decision:
Initial Page Load Time:
SSR: Generally provides faster initial page load times since the server
generates the HTML and sends a fully-rendered page to the client.
CSR: May result in slower initial page loads as the client needs to download
the JavaScript bundle and then render the content.
SEO (Search Engine Optimization):
SSR: Improves SEO, as search engines can easily crawl and index the content
present in the initial HTML response.
CSR: Requires additional efforts (like using techniques such as server-side
rendering for critical pages) to ensure better SEO.
User Experience:
SSR: Typically provides a faster perceived page load time, especially on
slower network connections, as the initial HTML content is already present.
CSR: Can lead to a faster transition between pages once the initial load is
complete due to client-side navigation.
Complexity of Development:
SSR: May have a simpler development model, as there's no need to manage
client-side rendering and hydration.
CSR: Can be more complex, especially when dealing with data fetching, state
management, and handling client-side routing.
Data Fetching:
SSR: Easier to handle initial data fetching on the server side, which can lead to
better performance and avoid additional round trips.
CSR: Requires additional client-side requests for data, which can result in
longer wait times for users.
Resource Utilization:
SSR: Places more load on the server, especially for rendering dynamic content
for each request.
CSR: Offloads rendering to the client, reducing the server load but potentially
requiring more client-side resources.
Client-Side Interactivity:
SSR: May provide a smoother initial interactivity, as the browser receives a
fully rendered page.
CSR: Allows for more dynamic and interactive client-side experiences,
especially for applications with frequent updates.
Deployment and Scaling:
SSR: Deployment and scaling may involve managing server instances
efficiently to handle the rendering load.
CSR: Can leverage Content Delivery Networks (CDNs) to distribute the client-
side bundle globally for faster access.
Browser Compatibility:
SSR: Generally more browser-compatible, as it relies less on client-side
JavaScript execution.
CSR: Requires more consideration for browser compatibility, especially for
older browsers or devices with limited JavaScript support.
Hydration:
SSR: No need for client-side hydration, as the HTML is already fully rendered
on the server.
CSR: Requires hydration to attach event listeners and make the client-side
content interactive.
Ultimately, the decision between SSR and CSR depends on your specific
project requirements, goals, and the trade-offs you are willing to make. Hybrid
approaches, such as Server-Side Rendering for the initial page and Client-Side
Rendering for subsequent interactions, are also possible (e.g., Next.js with
incremental static regeneration or Gatsby with server-side rendering). It's
essential to carefully analyze your application's needs and performance
characteristics before making a decision.
*********************************************************************
33. What is A11y issues? How to handle it?
 A11y, short for "accessibility," refers to the design and development
practices that ensure digital products, websites, and applications are
usable by people with disabilities. A11y issues encompass a range of
challenges that individuals with disabilities may face when interacting with
digital content. Common accessibility issues include difficulties for users
with visual, auditory, motor, or cognitive impairments.
Here are some key categories of A11y issues and strategies to handle them:
Visual Impairments:
Issue:
 Users with visual impairments may struggle with small text, low
contrast, or missing alternative text for images.
Handling:
 Ensure proper text contrast.
 Use scalable fonts and allow users to adjust text size.
 Provide meaningful alternative text for images using the alt attribute.
Auditory Impairments:
Issue:
 Users with hearing impairments may miss audio cues or content
presented only in audio format.
Handling:
 Provide captions or transcripts for audio and video content.
 Ensure important information is not conveyed only through sound.
Motor and Mobility Impairments:
Issue:
 Users with motor impairments may struggle with complex navigation or
interactive elements.
Handling:
 Ensure the website or application is navigable using a keyboard.
 Avoid relying solely on mouse events; make interactive elements
accessible via keyboard input.
 Provide larger clickable areas for touch interfaces.
Cognitive and Learning Disabilities:
Issue:
 Users with cognitive impairments may have difficulty understanding
complex content or navigating through cluttered interfaces.
Handling:
 Simplify language and use clear, concise content.
 Provide consistent navigation and layout.
 Allow users to customize the presentation or layout of content.
Accessibility Tools and Assistive Technologies:
Issue:
 Some users rely on assistive technologies like screen readers or voice
recognition software.
Handling:
 Ensure compatibility with screen readers by using semantic HTML
elements.
 Test your content with different assistive technologies.
Forms and Input Fields:
Issue:
 Users may face challenges when completing forms, especially if they are
poorly structured or lack proper labels.
Handling:
 Use descriptive labels and placeholders for input fields.
 Group related form elements together and provide clear instructions.
Focus and Keyboard Navigation:
Issue:
 Users who navigate using a keyboard may encounter issues if the focus
order is unclear or if interactive elements lack proper focus styles.
Handling:
 Ensure a logical and intuitive focus order.
 Use visible focus styles for interactive elements.
Testing and User Feedback:
Issue:
 A lack of regular testing and feedback from users with disabilities can
lead to undetected accessibility issues.
Handling:
 Conduct regular accessibility audits and testing using automated tools
and manual testing.
 Gather feedback from users with disabilities to identify and address
specific issues.
Educating Development Teams:
Issue:
 Lack of awareness or understanding of accessibility best practices
among development teams.
Handling:
 Provide training on accessibility guidelines (e.g., WCAG - Web Content
Accessibility Guidelines).
 Encourage a culture of accessibility within the development team.
Keeping Up with Standards:
Issue:
 Evolving standards and technologies may introduce new challenges for
accessibility.
Handling:
 Stay informed about the latest accessibility standards and best practices.
 Update and adapt your codebase as new technologies and guidelines
emerge.
 Incorporating accessibility into the development process from the beginning,
providing ongoing training, and leveraging testing tools are essential strategies
to address A11y issues effectively. Additionally, seeking feedback from users
with disabilities and involving them in the testing process can offer valuable
insights and help create more inclusive digital experiences.
*********************************************************************
34. What is Selective Hydration?
 Selective Hydration, also known as Partial Hydration, is a concept related
to Server-Side Rendering (SSR) in the context of web applications,
especially those built with frameworks like React.
In a traditional SSR approach, the server renders the entire HTML content,
including the initial state and UI, and sends it to the client. The client receives
the fully-rendered HTML, along with the necessary JavaScript bundle. When
the JavaScript runs on the client, it "hydrates" the existing HTML, attaching
event listeners and making the UI interactive.
Selective Hydration introduces a more optimized approach. Instead of
hydrating the entire HTML on the client side, selective hydration involves
identifying specific portions of the HTML that need to be made interactive and
deferring the hydration of non-essential parts.
This approach can be beneficial for improving the perceived performance and
reducing the time it takes for a web application to become interactive. It allows
developers to prioritize the hydration of critical or visible portions of the page
while deferring the hydration of less crucial components.
Here's a basic overview of how Selective Hydration works:
Initial Server-Side Rendering:
 The server performs the initial rendering of the HTML content,
including the critical UI components and state.
 The server sends this fully-rendered HTML to the client.
JavaScript Bundle:
 Along with the HTML, the server sends the JavaScript bundle required
for client-side interactivity.
Selective Hydration:
 The client-side JavaScript selectively hydrates specific portions of the
HTML that require interactivity.
 The hydration process attaches event listeners and initializes the client-
side state for those components.
Deferred Hydration:
 Non-critical or hidden components are left unhydrated initially.
 The hydration of these components is deferred until they become visible
or necessary for user interaction.
 Selective Hydration is often used in modern web development
frameworks, such as React. React 18 introduces features like automatic
batching and concurrent rendering, making it more efficient to
implement selective hydration.

Benefits of Selective Hydration include:


 Faster Time-to-Interactive: Prioritizing the hydration of critical components
can lead to a faster perceived performance for users.
 Reduced Initial JavaScript Payload: By deferring the hydration of non-essential
components, the initial JavaScript payload can be reduced, improving the initial
load time.
 Improved Perceived Performance: Users can interact with visible and critical
parts of the page sooner, creating a more responsive user experience.
 Selective Hydration is part of the ongoing efforts in web development to
optimize performance, especially in scenarios where large and complex web
applications need to be delivered efficiently to users.
*********************************************************************
35. Crawlers, indexing a page and what are the ways?
 Crawlers, also known as web spiders or bots, are automated programs used by
search engines to browse the web, collect information from websites, and index
their content. The process of crawling and indexing is crucial for search
engines to provide relevant and up-to-date search results. Here's an overview of
how crawlers work and the ways in which web pages are indexed:
1. Crawling:
 Crawling is the process of systematically browsing the web to discover
and collect information from web pages. Search engine crawlers
navigate from one page to another by following links found on each
page.
 Crawlers start with a set of known seed URLs and use various
algorithms to discover new URLs by parsing the content and extracting
links.
 The crawling process involves visiting web pages, downloading their
content, and extracting relevant information.
2. Indexing:
 Indexing is the process of organizing and storing the collected
information in a structured manner to facilitate fast and efficient
retrieval when users perform a search.
 The information gathered during crawling is processed, and key
elements such as keywords, metadata, and links are extracted and stored
in a searchable index.
 The index allows search engines to quickly identify relevant pages in
response to user queries.
Ways in Which Web Pages Are Indexed:
URL Submission:
 Website owners can submit their URLs directly to search engines
through their webmaster tools or search console interfaces. This ensures
that the search engine is aware of the existence of the page and can
initiate the crawling process.
XML Sitemaps:
 XML sitemaps provide a list of URLs on a website, along with
additional metadata such as the last modification date and priority.
Search engines use these sitemaps to discover and prioritize the crawling
of pages.
Internal Link Structure:
 Crawlers rely heavily on internal links within a website to discover and
navigate through different pages. A well-structured internal link system
enhances the discoverability of pages.
External Links (Backlinks):
 Pages that are linked to from external websites (backlinks) are often
prioritized by search engines. External links act as signals of relevance
and importance, influencing the crawling and indexing of pages.
HTML Meta Tags:
 Meta tags in the HTML head section of web pages, such as <meta
name="robots" content="index, follow">, provide instructions to search
engine crawlers regarding indexing and following links.
Dynamic XML Feeds:
 Websites with dynamic content, such as news websites or blogs, may
use XML feeds to provide real-time updates to search engines. These
feeds contain information about new content or changes on the site.
Social Media Signals:
 Social media platforms can influence the crawling and indexing of
pages. Content shared on social media may be discovered and indexed
more quickly by search engines.
Content Changes and Updates:
 Regularly updating and adding fresh content to a website signals to
search engines that the site is active and relevant. This can lead to more
frequent crawling and indexing.
Mobile-Friendly Pages:
 Search engines prioritize mobile-friendly pages. Having a responsive
design or a separate mobile version of a website can positively impact
crawling and indexing.
 It's important for website owners to optimize their sites for search
engine crawling and indexing to ensure that their content is accurately
and efficiently included in search results. Following best practices,
maintaining a crawlable site structure, and leveraging SEO techniques
contribute to better visibility in search engine results pages (SERPs).
*********************************************************************
36. Explain Redux Architecture?
 Redux is a state management library commonly used with React to manage the
state of an application in a predictable way. It follows a unidirectional data
flow and is based on three fundamental principles: a single source of truth, state
is read-only, and changes are made through pure functions.
Here's an overview of the key concepts and architecture of Redux:
1. Store:
 The store is a centralized, single source of truth for the state of the entire
application.
 It holds the application state as a plain JavaScript object.
 The state within the store is read-only, and changes are made by
dispatching actions.
2. Actions:
 Actions are plain JavaScript objects that describe changes in the
application state.
 They must have a type property indicating the type of action being
performed.
 Additional data or payload can be included to provide context for the
action.
3. Reducers:
 Reducers are pure functions responsible for specifying how the state
changes in response to actions.
 They take the current state and an action as arguments and return the
new state.
 Reducers must be pure functions, meaning they do not mutate the state
directly and always return a new state.
4. Action Creators:
 Action creators are functions that create and return action objects.
 They encapsulate the logic for creating actions, making it easier to
maintain and reuse action logic.
5. Middleware:
 Middleware provides a third-party extension point between dispatching
an action and the moment it reaches the reducer.
 It allows developers to intercept and modify actions, perform
asynchronous operations, or add additional functionality to the Redux
workflow.
 Common middleware includes redux-thunk for handling asynchronous
actions.
Redux Data Flow:
Action Dispatch:
 An action is dispatched using the store.dispatch(action) method.
Middleware (Optional):
 Middleware intercepts the action before it reaches the reducer.
Middleware can modify the action or perform asynchronous operations.
Reducer:
 The reducer takes the current state and the action, and it returns the new
state.
 Reducers are pure functions and should not mutate the state directly.
Store Update:
 The store updates its state with the new state returned by the reducer.
 Subscribers to the store are notified of the state change.
Example:
Let's consider a simple Redux architecture example:
// Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
// Action Creators
const increment = () => ({ type: INCREMENT });
const decrement = () => ({ type: DECREMENT });
// Reducer
const counterReducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
// Store
const { createStore } = require('redux');
const store = createStore(counterReducer);
// Dispatch Actions
store.dispatch(increment());
console.log(store.getState()); // Output: 1
store.dispatch(decrement());
console.log(store.getState()); // Output: 0
In this example, the store holds the state (a counter) and can be updated by
dispatching actions (increment or decrement). The reducer specifies how the
state changes in response to these actions. This simple example demonstrates
the core principles of the Redux architecture.
*********************************************************************
37. How will you set redirects using axios library?
 Axios is primarily an HTTP client library for making requests, and it doesn't
inherently handle redirects like a browser does. However, you can manage
redirects by checking the HTTP status codes received in the response and
manually following the redirect if needed.
Here's a simple example using Axios and handling redirects:
const axios = require('axios');
const makeRequest = async (url, maxRedirects = 5) => {
let currentUrl = url;
let redirects = 0;
while (redirects < maxRedirects) {
try {
const response = await axios.get(currentUrl);
// Check if it's a redirect (3xx status code)
if (response.status >= 300 && response.status < 400) {
// Extract the new URL from the 'Location' header
currentUrl = response.headers.location;
redirects++;
} else {
// Successfully fetched the content (2xx status code)
console.log(`Successfully fetched content from: ${currentUrl}`);
return response.data;
}
} catch (error) {
// Handle errors (e.g., network issues, timeouts)
console.error(`Error fetching content from ${currentUrl}:`,
error.message);
throw error;
}
}
// Maximum number of redirects reached
console.error(`Maximum number of redirects (${maxRedirects})
reached`);
return null;
};
// Example usage
const targetUrl = 'http://example.com';
makeRequest(targetUrl)
.then((content) => {
// Process the content as needed
console.log(content);
})
.catch((error) => {
// Handle errors
console.error(error);
});
In this example:
The makeRequest function takes a URL and an optional maxRedirects
parameter.
It repeatedly makes HTTP GET requests and checks the response status.
If the status is in the 3xx range, it extracts the new URL from the 'Location'
header and follows the redirect.
If the status is in the 2xx range, it logs a success message and returns the
content.
The function limits the number of redirects to avoid potential infinite loops.
Keep in mind that handling redirects manually might not cover all edge cases,
and it's important to tailor this logic based on the specific requirements and
behavior of the endpoints you are working with. If you are dealing with
complex redirects or need more sophisticated handling, consider using a library
like follow-redirects with Axios.
*********************************************************************
38. How Babel work?
 Babel is a JavaScript compiler that allows developers to write code using the
latest ECMAScript (ES) features and syntax, while ensuring compatibility with
older browsers and environments that may not support these features.
 Babel operates on the principle of transpilation, which involves transforming
source code written in one version of JavaScript into an equivalent version that
can be executed in a different environment.
Here's an overview of how Babel works:
Parsing (Lexical Analysis):
 Babel starts by parsing the input JavaScript code using a lexer (lexical
analyzer).
 The lexer breaks down the source code into a stream of tokens,
representing the smallest units of the code, such as keywords,
identifiers, operators, and literals.
Abstract Syntax Tree (AST) Generation:
 Babel then constructs an Abstract Syntax Tree (AST) from the stream of
tokens.
 The AST is a hierarchical representation of the syntactic structure of the
code, where each node corresponds to a specific language construct
(e.g., a variable declaration, a function call, etc.).
Transformation:
 Babel applies a set of plugins that perform transformations on the AST.
 Each plugin is responsible for handling specific language features or
syntax transformations.
 Transformations may include converting newer ES features to
equivalent older versions, adding polyfills, or applying custom logic.
AST Rebuilding:
 After applying transformations, Babel rebuilds the AST to reflect the
changes made by the plugins.
 The transformed AST now represents the code in a version compatible
with the specified target environment.
Code Generation:
 Babel generates the final JavaScript code from the transformed AST.
 The code is generated in a format that is compatible with the target
environment or the specified ECMAScript version.
Output:
 The final transpiled code is output as a string, ready to be executed in
the target environment.
 Developers can configure Babel to generate separate files or bundle the
output using additional tools like bundlers (e.g., Webpack).
Example:
Let's consider an example of using Babel to transpile modern JavaScript code
(ES6+) to ES5:
Install Babel Packages:
npm install @babel/core @babel/cli @babel/preset-env --save-dev
Create a .babelrc Configuration File:
{
"presets": ["@babel/preset-env"]
}
Write Modern JavaScript Code (e.g., index.js):
const add = (a, b) => a + b;
console.log(add(2, 3));
Run Babel:
npx babel index.js --out-file output.js
This command transpiles index.js to ES5 and outputs the result to output.js.
Babel's flexibility and extensibility come from its plugin system. Developers
can customize the transformation process by adding or creating their own
plugins, allowing for tailored solutions to specific use cases or environments.
*********************************************************************
39. Explain Webpack, parcel and some it’s features
 Webpack and Parcel are both popular bundlers in the JavaScript ecosystem,
used to bundle and optimize web assets like JavaScript, CSS, and images. They
share common goals, but there are differences in their approaches and features.
Webpack:
Key Features:
Module System:
 Webpack treats all assets (JavaScript, CSS, images) as modules,
allowing developers to use the import and require syntax to manage
dependencies.
Code Splitting:
 Webpack allows for code splitting, enabling the creation of smaller
bundles that can be loaded on-demand, improving page load times.
Loaders:
 Webpack uses loaders to transform and process different types of files.
For example, Babel can be used as a loader for transpiling JavaScript,
and CSS loaders for processing styles.
Plugins:
 Webpack has a rich ecosystem of plugins that extend its functionality.
Plugins can perform tasks like minification, code splitting, and
optimization.
Hot Module Replacement (HMR):
 Webpack supports HMR, allowing developers to see the changes in real-
time without a full page refresh during development.
Advanced Configuration:
 While powerful, Webpack configurations can be complex. Webpack
requires a detailed configuration file to define entry points, output paths,
loaders, and plugins.
Parcel:
Key Features:
Zero Configuration:
 One of the standout features of Parcel is its zero-configuration setup.
Developers can start using Parcel without creating a configuration file,
making it beginner-friendly.
Automatic Asset Detection:
 Parcel automatically detects and transforms assets based on their types.
It supports various file types out of the box, requiring minimal manual
configuration.
Code Splitting:
 Similar to Webpack, Parcel supports code splitting, allowing developers
to create smaller bundles for better performance.
Hot Module Replacement (HMR):
 Parcel includes built-in support for HMR, simplifying the process of
seeing changes in real-time during development.
Advanced Features Without Configuration:
 Parcel provides advanced features like tree shaking, scope hoisting, and
caching without the need for manual configuration.
Fast Bundle Times:
 Parcel aims for fast bundle times by utilizing parallelization and
optimizing the bundling process.
Comparison:
Configuration:
Webpack:
 Requires a detailed configuration file for defining entry points, output
paths, loaders, and plugins.
Parcel:
 Offers zero-configuration, making it easier for beginners. Configuration
is automatically handled based on the project structure.
Setup and Learning Curve:
Webpack:
 Has a steeper learning curve due to its extensive configuration options.
Parcel:
 Has a lower learning curve, and developers can start using it quickly
with minimal setup.
Flexibility:
Webpack:
 Highly flexible and customizable due to its extensive configuration
options and plugin system.
Parcel:
 Offers less configuration but aims to provide a simpler and more
intuitive developer experience.
Ecosystem:
Webpack:
 Has a mature and extensive ecosystem with a large number of plugins
and loaders.
Parcel:
 Has a growing ecosystem, and while it may not match Webpack's
breadth, it covers common use cases effectively.
 Both Webpack and Parcel are powerful tools, and the choice between them
depends on project requirements, developer preferences, and the desired level
of configuration flexibility. Developers often choose Parcel for its simplicity
and quick setup, while Webpack is preferred for larger projects with specific
optimization needs and complex setups.
*********************************************************************
40. Challenges with React?
 While React is a powerful and widely used JavaScript library for building user
interfaces, developers may encounter various challenges while working with it.
Here are some common challenges associated with React:
Learning Curve:
 For newcomers, especially those new to JavaScript frameworks or
libraries, there can be a steep learning curve when getting started with
React. Concepts like JSX, components, state, and props may take time
to grasp.
State Management:
 Managing state in larger applications can become challenging. As
applications grow, finding the right balance between local and global
state, as well as choosing the appropriate state management solution
(e.g., Context API, Redux), becomes crucial.
Component Lifecycle:
 Understanding and managing the component lifecycle can be complex.
Developers need to be aware of when to use lifecycle methods and how
to handle side effects properly (e.g., using componentDidMount or
useEffect).
Prop Drilling:
 Passing data between deeply nested components can result in prop
drilling, where props are passed through multiple layers of components.
This can make the code less maintainable and harder to debug.
Conditional Rendering:
 Conditional rendering can become challenging when dealing with
complex UI logic. Determining when and where to conditionally render
components or elements might require careful consideration.
Performance Optimization:
 Achieving optimal performance in React applications can be a
challenge. Understanding and implementing techniques like
memoization, virtualization, and avoiding unnecessary renders is
essential for maintaining a smooth user experience.
Global State Management:
 While React provides a local state for components, managing global
state across the entire application can be challenging. Different state
management solutions (e.g., Redux, Recoil) have their own trade-offs,
and choosing the right one is crucial.
Integration with Back-End:
 Integrating React with back-end technologies and handling data fetching
can present challenges. Deciding how to structure API calls, manage
data, and handle asynchronous operations requires thoughtful
consideration.
SEO (Search Engine Optimization):
 React applications that heavily rely on client-side rendering may face
SEO challenges. Proper server-side rendering (SSR) or using
technologies like Next.js can address these issues.
Tooling and Configuration:
 Setting up and configuring build tools (e.g., Webpack, Babel) and other
development tools might be challenging for beginners. Managing
dependencies and keeping the build process efficient can be crucial for
development workflows.
React Hooks Adoption:
 While React introduced hooks to simplify state management and side
effects, developers who are used to class components might find the
transition challenging. Understanding hooks like useState and useEffect
can take time.
Security Concerns:
 React applications may be susceptible to security issues like Cross-Site
Scripting (XSS) if proper precautions are not taken. Escaping user input
and sanitizing data are critical for preventing such vulnerabilities.
 Despite these challenges, React has a large and supportive community, and
many resources are available to help developers overcome difficulties and
enhance their React development skills. Additionally, ongoing improvements
and updates to React itself address some of these challenges and introduce new
features to improve developer workflows.
*********************************************************************
41. Memoization Techniques, pure functions and pure component?

*********************************************************************
42. ES-lint and security plugins used in project?

*********************************************************************
43. Various hooks syntax useParams, useReducer, useQuery, useConext and
many more…

*********************************************************************
44. As there is real dom already there why we need to use virtual dom? which
dom will render first virtual or real?
 React Virtual DOM vs Real DOM
What is DOM?
“The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document.”

 The DOM is an abstraction of a page’s HTML structure.


 It takes HTML elements and wraps them in an object with a tree-
structure — maintaining the parent/child relationships of those nested
HTML elements.
 This provides an API that allows us to traverse nodes (HTML elements)
and manipulate them in a number of ways — such as adding nodes,
removing nodes, editing a node’s content, etc.
DOM inefficiency

 DOM was originally intended for static UIs, pages rendered by the
server that don’t require dynamic updates.
 When the DOM updates, it has to update the node as well as re-paint the
page with its corresponding CSS and layout. Say we have an array.
let fruits = [‘Apple’, ‘Orange’, ‘Banana’]

 We want to update here from Orange to lemon. Then we need to create a


new array.
let fruits = [‘Apple’, ‘Lemon’, ‘Banana’]
In an efficient way we can just traverse to the fruits[2] and update only this
element.
Now it’s common to have a thousands node in a single SPA. So repaint the
whole page for each change is very-very expensive.
Ideally, we’d like to only re-render items that receive updates, leaving the rest
of the items as-is.
Knowing when to update
There are a couple of ways in which components can tell when a data update
occurs and whether or not it needs to re-render to the UI:
Dirty Checking (slow) — Checks through all node’s data at a regular interval
to see if there have been any changes. This is inefficient because it requires
traversing every single node recursively to make sure it’s data isn’t “dirty” (out
of date). This was used in AngularJS 1.x.
Observable (fast) — Components are responsible for listening to when an
update takes place. Since the data is saved on the state, components can simply
listen to events on the state and if there is an update, it can re-render to the UI.
React uses it.
Virtual DOM

 The Virtual DOM is a light-weight abstraction of the DOM.


 You can think of it as a copy of the DOM, that can be updated without
affecting the actual DOM.
 It has all the same properties as the real DOM object, but doesn’t have
the ability to write to the screen like the real DOM.
 The virtual DOM gains it’s speed and efficiency from the fact that it’s
lightweight. In fact, a new virtual DOM is created after every re-render.
 Reconciliation is a process to compare and keep in sync the two files
(Real and Virtual DOM). Diffing algorithm is a technique of
reconciliation which is used by React.
Is the Shadow DOM the same as the Virtual DOM?

 No, they are different. The Shadow DOM is a browser technology


designed primarily for scoping variables and CSS in web components.
The virtual DOM is a concept implemented by libraries in JavaScript on
top of browser APIs.
How does updates work in React?

 On the first load, ReactDOM.render() will create the Virtual DOM tree
and real DOM tree.
 As React works on Observable patterns, when any event(like key press,
left click, api response, etc.) occurred, Virtual DOM tree nodes are
notified for props change, If the properties used in that node are updated,
the node is updated else left as it is.
 React compares Virtual DOM with real DOM and updates real DOM.
This process is called Reconciliation. React uses Diffing algorithm
techniques of Reconciliation.
 Updated real DOM is repainted on browser.
Additional points regarding updates.

 Virtual DOM is pure JS file and light weight, So capturing any update in
Virtual DOM is much faster than directly updating on Real DOM.
 React takes a few milliseconds before reconciliation.
 This allows react to bundle few processes.
 This increases efficiency and avoids unnecessary reprocessing. Because
of this delay we should not rely on this.state.val just after setState().
 React does shallow comparison of props value. We need to handle deep
comparison separately, immutable is the most common way to handle it.
*********************************************************************
45. Make a automated Time using React?
*********************************************************************
46. Diff between functional and class components?

Functional Component Class Component
1) Simple Function 1) More feature rich
2) Use functional component as much as 2) Maintain their own private data-state
possible.
3) Absence of ‘this’ keyword. 3) Complex UI logic
4) Solution without using state 4) Provide life cycle hooks
5) Mainly responsible for UI 5) Stateful /smart/container
6) Stateless/ Dumb / Presentational
*********************************************************************
47. Explain life cycle methods in order
 1) Mounting
2) Updating
3) Unmounting
4) Error Handling
Mounting: When an instance of a component is being created and inserted into
the DOM.
Updating: When a component is being re-rendered as a result of changes to
either its props or state.
Unmounting: When a component is being removed from the DOM.
Error Handling: When there is an error during re-rendering, in life cycle
method, or in the constructor of any child component.
Mounting: (Methods)
1. Constructor
2. Static getDerivedStateFromProps
3. render
4. componentDidMount
Updating: (Methods)
1. static getDerivedStateFromProps
2. shouldComponentUpdate
3. render
4. getSnapShotBeforeUpdate
5. componentDidUpdate
Unmounting: (Methods)
1. componentWillUnmount
ErrorHandling: (Methods)
1. Static getDerivedStateFromError
2. componentDidCatch
Mounting LifeCycle Methods
 constructor(props):
1) A special function will get called whenever a new component is
created.
2) Initializing state
3) Binding the event handlers
4) Did not cause side effects, ex- http request, we can not call Http
request through constructor.
5) super(props) we need to call inside constructor which is called base
class constructor.
6) Directly overwrite this.state
 static getDerivedStateFromProps:
1) When the state of the component depends on changes in props over
time.
2) Set the state
3) Do not cause side effects ,Ex. Http request
 render():
1) Only method required in class component.
2) Read props and state & return JSX.
3) Do not change state or interact with DOM or make ajax calls.
4) Children components lifecycle methods are also executed.
 compnentDidMount:
1) This method is executed only once in component life cycle.
2) This method invoked immediately after a component and all its
children component have been rendered to the DOM.
3) Cause side effect , Ex. Interaction with the DOM or perform any ajax
calls to load data
Updating Lifecycle Methods:
 static getDerivedStateFromProps(props, state):
1) Method is called every time a component is re-rendered.
2) Set the state (when state depends on props)
3) Do not cause side effect. Http request.
 shouldComponentUpdate
1) Dictates if the component should re-render or not.
2) Perform optimization.
3) Do not cause side effects. Ex Http request calling the setState method.

 getSnapShotBeforeUpdate(prevProps, prevState):
1) Called right before the changes from the virtual DOM are to be
reflected in the DOM.
2) capture some information from the DOM.
3)Method will either return null or return a value. Returned value will be
passed as the third parameter to the next method.

 componentDidUpdate(prevProps, prevState, snapShot):


1) Called after the render is finished in the re-render cycles.
2) This method call only once in each re-render cycle.
3) cause side effects.
 Unmounting Phase Method:
componentWillUnmount():
1) Method is invoked immediately before a component is unmounted and
destroyed.
2) Cancelling any network requests, removing event handlers, cancelling
any subscriptions and also invalidating timers.
3) Do not call the setState method.
 Error Handling Phase Methods:
static getDerivedStateFromError(error):
componentDidCatch:
1) When there is an error during rendering in a lifecycle method, or in
the constructor of any child component
*********************************************************************
3) What r important concepts in react hooks
 https://www.bigscal.com/blogs/frontend-technology/basic-concept-of-
reactjs-hooks/
****************************************************************
*****4) What happens if setState is used inside render method

 You can not set state inside render function because it will cause side
effect.
 What exactly happens is that each time you update state react calls render
function, so if you will update state inside render function then it will
stuck inside infinite loop.
****************************************************************
*****5) Explain useEffect()

****************************************************************
*****6) What r Refs in react and show an example(code)

 With the help of refs you can access DOM nodes directly into react.
 Refs cannot attached to functional component using createRef()
Example:
Class RefsDemo extends Component{
constructor(props){
super(props)
this.inputRefs = React.createRef()
}
componentDidMount(){
this.inputRefs.current.focus()
console.log(this.inputRefs)
}
handleClick = ()=>{
alert(this.inputRefs.current.value)
}

render(){
<>
<input type=”text” ref={this.inputRefs}/>
<button onClick={this.handleClick}>
Click me
</button>
</>
}
}
export default RefsDemo
****************************************************************
*****7) What is the use of dangerouslySetInnerHTML?
 The `dangerouslySetInnerHTML` attribute is React's replacement for
using `innerHTML` in the browser DOM.
 Just like `innerHTML`, it is risky to use this attribute considering cross-
site scripting (XSS) attacks. You just need to pass a `__html` object as
key and HTML text as value.
In this example MyComponent uses `dangerouslySetInnerHTML`
attribute for setting HTML markup:
function createMarkup() {
return { __html: 'First &middot; Second' }
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />
}
****************************************************************
*****8) Why we shouldn’t update state directly?
 If you try to update the state directly then it won't re-render the component.
//Wrong
this.state.message = 'Hello world'
Instead use `setState()` method. It schedules an update to a component's state
object. When state changes, the component responds by re-rendering.
//Correct
this.setState({ message: 'Hello World' })
Note: You can directly assign to the state object either in constructor or using
latest javascript's class field declaration syntax.

****************************************************************
*****9) Explain Redux workflow?

****************************************************************
*****TCS:
10) Advantages/ Disadvantages of react?

Below are the list of main Advantages of React,
1. Increases the application's performance with *Virtual DOM*.
2. JSX makes code easy to read and write.
3. It renders both on client and server side (*SSR*).
4. Easy to integrate with frameworks (Angular, Backbone) since it is only
a view library.
5. Easy to write unit and integration tests with tools such as Jest.
Disadvantages/limitations of react
1. React is just a view library, not a full framework.
2. There is a learning curve for beginners who are new to web
development.
3. Integrating React into a traditional MVC framework requires some
additional configuration.
4. The code complexity increases with inline templating and JSX.
5. Too many smaller components leading to over engineering or
boilerplate.

****************************************************************
*****11) What is entry point of react Application?
 index.js
****************************************************************
*****12) What is HOC? Where u have used/written in your project?
 A higher-order component (HOC) is a function that takes a component
and returns a new component.
 Basically, it's a pattern that is derived from React's compositional nature .
 We call them pure components because they can accept any dynamically
provided child component but they won't modify or copy any behaviour
from their input components.
const EnhancedComponent =
higherOrderComponent(WrappedComponent)
HOC can be used for many use cases:
1. Code reuse, logic and bootstrap abstraction.
2. Render hijacking.
3. State abstraction and manipulation.
4. Props manipulation.

****************************************************************
***** 13) What is React Context API? And when to use
 Context provides a way to pass data through the component tree without
having to pass props down manually at every level.
****************************************************************
***** 14) How do u handle API calls in your react app? Axios ?
1. The Fetch API
Fetch API is built into most modern browsers on the window object
(window.fetch), and enables us to easily make HTTP requests.
The following code snippets show a simple example of Fetch API in practice:
import {useEffect} from "react";
const fetchUsers = () => {
// Where we're fetching data from map
return fetch("http://www.abc.cd/test")
// We get the API response and receive data in JSON format
.then((response) => response.json())
.then((data) => console.log(data))
.catch ((error) => console.error(error));}
The only goal of this function is to access the data and convert the response into
JSON using the response.json() method. Here, the JSON() method is used to get
the response object stored in the data and update the users’ state in our
application.
Fetch is promise-based, which means we can also catch errors using the .catch()
method. Any encountered error is used as a value to update our error’s state.
Now, adding to that, we will make this request, within the useEffect() hook,
with an empty dependencies array as the second argument. This is done so that
our request is only made once and is not dependent on any other data.
Here is an example how to use it in the useEffect() hook:
import {useEffect} from "react";
useEffect(() => {
fetchData()
}, []);
Isn’t this handy? Let’s see what the other methods do.
2. Axios library
Axios is a Promise-based HTTP client for JavaScript that can be used in your
front-end application and Node.js backend.
When using Axios, it’s easy to send asynchronous HTTP requests to REST
endpoints and perform CRUD operations.
In this example, we first have to install Axios using npm or yarn. Then, we will
add it as an import to our parent component.
npm install axios
The following code snippets show an example of how to use Axios:
import axios from "axios"
const fetchData = () => {
return axios.get("http://www.abc.cd/test")
.then((response) => console.log(response.data));
}
Similar to the Fetch API, Axios also returns a promise. However, in Axios, it
always returns a JSON response. The coding part is similar to the Fetch API,
except that it has shorter steps and better error handling.
Check out the official documentation for more information.
3. async/await syntax
async/await is a relatively new way to synchronously write asynchronous code.
When the async keyword is place before a function, it has two effects:
Makes it always return a promise.
Allows await to be used within it.
The await keyword before a promise makes JavaScript wait until that promise
settles, and then:
If it’s an error, the exception is generated.
Otherwise, it returns the result.
Take a look at the following code snippets:
async function fetchData() {
try {
const result = await axios.get("http://www.abc.cd/test")
console.log(result.data));
} catch (error) {
console.error(error);
}
}
When we use useEffect(), the effect function cannot be made an async function.
For that, we can create a separate async function in our component that we can
synchronously call within useEffect and fetch our data accordingly.
4. React-query library
React-query is a great library that solves the problem of managing server state
and caching in applications.
"It makes fetching, caching, synchronizing, and updating server state in your
React applications a breeze.”
Firstly, let’s install the required package:
npm install react-query react-query-devtools
Note: React-query also has its own dev tools that help us to visualize the inner
workings of React-query.
React-query gives us a cache that you can see below through the React Query
Devtools. This cache enables us to easily manage the requests we have made
according to the key-value we specify for each request.
import React from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider, useQuery } from "react-query";
import { ReactQueryDevtools } from "react-query/devtools";
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<FetchData />
</QueryClientProvider>
);
}

function FetchData() {
const { data } = useQuery("UserData", () =>
fetch("http://www.abc.cd/test").then((res) => res.json())
);
return (
<div>
// data you want to show
<ReactQueryDevtools initialIsOpen />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In short, we need to tell the library where we need to fetch the data and it will
handle caching, background updates, and refresh data without any extra code or
configuration.
It also provides some hooks or events for mutation, queries to handle errors, and
other states of side effects that remove the need for useState() and useEffect()
hooks and replaces them with a few lines of React-query logic.
****************************************************************
***** 15) How will u chain multiple api calls that depends on previous request?
I need to chain a few API requests from the Google Maps API, and I'm trying
to do it with Axios.

Here is the first request, which is in componentWillMount()

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' +
this.props.p1)
.then(response => this.setState({ p1Location: response.data })) }
Here is the second request:

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' +
this.props.p2)
.then(response => this.setState({ p2Location: response.data }))
Then we have a third request, which is dependent on the first two being
completed:

axios.get('https://maps.googleapis.com/maps/api/directions/json?
origin=place_id:' + this.state.p1Location.results.place_id +
'&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' +
'API-KEY-HIDDEN')
.then(response => this.setState({ route: response.data }))
How can I chain these three calls so that the third happens after the first two?


First off, not sure you want to do this in your componentWillMount, it's better
to have it in componentDidMount and have some default states that will update
once done with these requests. Second, you want to limit the number of
setStates you write because they might cause additional re-renders, here is a
solution using async/await:

async componentDidMount() {

// Make first two requests


const [firstResponse, secondResponse] = await Promise.all([
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=$
{this.props.p1}`),
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=$
{this.props.p2}`)
]);

// Make third request using responses from the first two


const thirdResponse = await
axios.get('https://maps.googleapis.com/maps/api/directions/json?
origin=place_id:' + firstResponse.data.results.place_id +
'&destination=place_id:' + secondResponse.data.results.place_id + '&key=' +
'API-KEY-HIDDEN');

// Update state once with all 3 responses


this.setState({
p1Location: firstResponse.data,
p2Location: secondResponse.data,
route: thirdResponse.data,
});
}
****************************************************************
***** 16) How will u optimize a react application?

1) shouldComponentUpdate
2) Pure component
3) memo (useMemo /useCallback)
****************************************************************
***** 17) What is pure component? how will u implement same on functional
component?

https://www.geeksforgeeks.org/what-is-a-pure-functional-component-in-reactjs/#:~:text=A
%20function%20is%20said%20to,the%20same%20state%20and%20props .
****************************************************************
***** 18) Explain Controlled and uncontrolled component?
 Controlled Components:
 A component that controls the input elements within the forms on
subsequent user input is called Controlled Component, i.e, every state
mutation will have an associated handler function.
For example, to write all the names in uppercase letters, we use
handleChange as below,
handleChange(event) {
this.setState({value: event.target.value.toUpperCase()})
}
Uncontrolled Components :
 The Uncontrolled Components are the ones that store their own state
internally, and you query the DOM using a ref to find its current value
when you need it.
 This is a bit more like traditional HTML.
 In the below UserProfile component, the `name` input is accessed using
ref.
class UserProfile extends React.Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
this.input = React.createRef()
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value)
event.preventDefault()
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>{'Name:'}
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
)}
}
 In most cases, it's recommended to use controlled components to
implement forms.
 In a controlled component, form data is handled by a React component.
 The alternative is uncontrolled components, where form data is handled
by the DOM itself.
https://medium.com/tech-tajawal/controlled-and-uncontrolled-components-in-
react-6d5f260b46dd
****************************************************************
***** 19) Redux questions on reducers, actions and state

****************************************************************
***** 20) How to avoid mutating an array when performing an operation
 In JavaScript, there are many ways to store data, and one of them is the
array. We can store several pieces of data in one place in an array instead of
storing them in several spaces using variables.
Unlike strings and variables, arrays are mutable, or easily changed. They can be
changed freely, even if we use const in their declaration.
Here’s an example:
const myArray = [1, 2, 3, 4, 5, 6, 7];
console.log(myArray[0]);
myArray[0] = 9;
console.log(myArray[0]);
Array mutation
Explanation
Line 1: In the example above, we create an array named myArray and store 7
numbers in it.
Line 2: We access the first element of the array using the bracket notation and
print the result (1) to the console.
Line 3: We access the first element again using the same method in line 2 above
and assign it a new value (9).
Line 4: We access the first element again and print it to the console. The
console now prints 9, which is the new value assigned.
Despite how myArray was declared with const, the elements were still changed
freely. This shows that arrays are mutable.
The Object.freeze() function
To prevent the mutation of arrays and objects, JavaScript provides a function
Object.freeze() which prevents data from being changed easily. Any attempt to
change the data of objects and arrays will be rejected and the original values
will be used any time they are accessed across our code. Here’s an example:
const myArray = [1, 2, 3, 4, 5, 6, 7];
console.log(myArray[2]);
Object.freeze(myArray);
myArray[2] = 17;
console.log(myArray[2]);
Mutation prevention
Explanation
Line 1: We declare an array with const and assign it seven elements.
Line 2: We print the value of the third element of the array to the console by
accessing the value and using the console.log function.
Line 3: We pass myArray to the Object.freeze function to prevent it from
mutation.
Line 4: We access the third element again and assign it a new value.
Line 5: We access the third element again and print its value to the console.
Suprisingly, it still prints 3, which was its original value.
Conclusion
We can prevent mutation of objects and arrays using the Object.freeze()
JavaScript function. We pass the desired object or array as an argument to this
function, which later prevents any change to the object’s or array’s data.
This is very important and useful for developers who want to write functions
that work and don’t easily crash due to simple internal mutation.
****************************************************************
***** 21) Explain component Lifecycle method – Same on hooks

****************************************************************
***** 22) Why reducer is called as pure function?

 Reducers are just pure functions that take the previous state and an action,
and return the next state.
 Remember to return new state objects, instead of mutating the previous
state
****************************************************************
***** accenture
23) How do you implement pure component in Hooks?
 by using useMemo
****************************************************************
***** 24) When an unmounting of a component needed?
 Components are unmounted when the parent component is no longer
rendered or the parent component performs an update that does not render this
instance. ReactDOM.unmountComponentAtNode will also trigger an unmount.

****************************************************************
***** 25) Use of redux thunk?

 Redux Thunk is a popular middleware for React Redux. You can create
services that return a function hence the name Thunk. The creators of
Thunk call this function ‘action creators’. Here is a quote from GitHub:
 “Redux Thunk middleware allows you to write action creators that return
a function instead of an action.”
 For me personally, it makes more sense to think of these thunk functions
as services since they don’t return actions. Remember that actions are
plain objects. Your thunk function will call dispatch, so you’ll be calling
dispatch at least twice. Once from your component when you call your
service. And then again inside of your thunk function to trigger your
reducer.
 Redux Thunk looks for these special functions and handles the
dispatching for you. This pattern allows you to centralize and re-use these
services in different components. This especially comes handy when you
are making asynchronous API requests and you need to dispatch on
promise success and error.
 A common misconception is that with Redux you can’t dispatch actions
from within async calls. In fact, It’s technically possible, just not
recommended.
 For a detailed discussion:
 Here is an example of a login service that uses Thunk.
export const login = (email, password) => dispatch => {
dispatch(AuthReducer.setAuthPending());
return AuthApi.login(email, password)
.then(response => {
if (response.success) {
dispatch(
AuthReducer.setLoginSuccess(response.authToken,
response.refreshToken)
);
_saveItem(‘authToken’, response.authToken)
.then(resp => {
_saveItem(‘refreshToken’, response.refreshToken)
.then(resp => {
App.startAppLoggedIn();
})
.catch(error => {
dispatch(asyncError(error));
});
})
.catch(error => {
dispatch(asyncError(error));
});
} else {
dispatch(AuthReducer.setLoginError(response.message));
}})
.catch(error => {
dispatch(generalError(error));
});
};
In conclusion, Redux Thunk uses a pattern that promotes abstracting store logic
out of components and into services, action creators, and actions. Your
components shouldn’t care about what happens to the data store, all you need to
do is dispatch the login service. You want to use Thunk so you can do this:
function mapDispatchToProps(dispatch) {
return {
login: (email, password) => {
dispatch(login(email, password));
}
};
}
****************************************************************
***** Infosys
26) Where you will perform an API call if you need to get data before
componentDidMount?

 Calling API in constructor() or componentWillMount() is not a syntax


error but increases code complexity and hampers performance. So, to
avoid unnecessary re-rendering and code complexity, it's better to call
API after render(), i.e componentDidMount()
****************************************************************
***** 27) useMemo/ React memo difference

****************************************************************
***** 28) What is redux? When to use redux

 Redux is a predictable state container for JavaScript apps based on the


Flux design pattern.
 Redux can be used together with React, or with any other view library.
 It is tiny (about 2kB) and has no dependencies.
****************************************************************
***** 29) Few more questions on webpack /typescript

****************************************************************
***** LTI(L&T Infotech)

30) What is virtual Dom and how it increases performance?


 Virtual DOM

 The Virtual DOM is a light-weight abstraction of the DOM.


 You can think of it as a copy of the DOM, that can be updated without
affecting the actual DOM.
 It has all the same properties as the real DOM object, but doesn’t have the
ability to write to the screen like the real DOM.
 The virtual DOM gains it’s speed and efficiency from the fact that it’s
lightweight. In fact, a new virtual DOM is created after every re-render.
 Reconciliation is a process to compare and keep in sync the two files
(Real and Virtual DOM). Diffing algorithm is a technique of
reconciliation which is used by React.
Is the Shadow DOM the same as the Virtual DOM?

 No, they are different. The Shadow DOM is a browser technology


designed primarily for scoping variables and CSS in web components.
 The virtual DOM is a concept implemented by libraries in JavaScript on
top of browser APIs.
How does updates work in React?

 On the first load, ReactDOM.render() will create the Virtual DOM tree
and real DOM tree.
 As React works on Observable patterns, when any event(like key press,
left click, api response, etc.) occurred, Virtual DOM tree nodes are
notified for props change, If the properties used in that node are updated,
the node is updated else left as it is.
 React compares Virtual DOM with real DOM and updates real DOM.
This process is called Reconciliation. React uses Diffing algorithm
techniques of Reconciliation.
Updated real DOM is repainted on browser
****************************************************************
***** 31) Why do we need keys in react?

1. A `key` is a special string attribute you should include when creating
arrays of elements.
2. Key prop helps React identify which items have changed, are added, or
are removed.
 Most often we use ID from our data as key:
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)

 When you don't have stable IDs for rendered items, you may use the item
index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
<li key={index}>{todo.text}</li>)
Note: 1. Using indexes for keys is not recommended, if the order of items may
change. This can negatively impact performance and may cause issues with
component state.
2. If you extract list item as separate component then apply keys on list
component instead of `li` tag.
3. There will be a warning message in the console if the `key` prop is not
present on list items.
****************************************************************
***** 32) If we render a parent node does all of its child re-render?
 No. React will only re-render a component if shouldComponentUpdate()
returns true. By default, that method always returns true to avoid any subtle
bugs for newcomers (and as William B pointed out, the DOM won't actually
update unless something changed, lowering the impact).
To prevent your sub-component from re-rendering unnecessarily, you need to
implement the shouldComponentUpdate method in such a way that it only
returns true when the data has actually changed. If this.props.messages is
always the same array, it could be as simple as this:
shouldComponentUpdate(nextProps) {
return (this.props.messages !== nextProps.messages);
}
You may also want to do some sort of deep comparison or comparison of the
message IDs or something, it depends on your requirements.
EDIT: After a few years many people are using functional components. If that's
the case for you then you'll want to check out React.memo. By default
functional components will re-render every time just like the default behavior of
class components. To modify that behavior you can use React.memo() and
optionally provide an areEqual() function.
****************************************************************
***** 33) Uses of hooks and refs

****************************************************************
*****34) What is the diff between NextJS/ ReactJS?

****************************************************************
*****36) Different types of rendering in Next JS?

****************************************************************
*****37) Explain to me how React JS makes your current application better?
 Key benefits of react js for front-end development
Speed:

 The React basically allows developers to utilize individual parts of their


application on both client-side and the server-side, which ultimately
boosts the speed of the development process.
 In simple terms, different developers can write individual parts and all
changes made won’t cause the logic of the application.
Flexibility:

 Compared to other frontend frameworks, the React code is easier to


maintain and is flexible due to its modular structure. This flexibility, in
turn, saves huge amount of time and cost to businesses.
Performance:
 React JS was designed to provide high performance in mind. The core of
the framework offers a virtual DOM program and server-side rendering,
which makes complex apps run extremely fast.
Usability:

 Deploying React is fairly easy to accomplish if you have some basic


knowledge of JavaScript.
 In fact, an expert JavaScript developer can easily learn all ins and outs of
the React framework in a matter of a day or two.
Reusable Components:

 One of the main benefits of using React JS is its potential to reuse


components. It saves time for developers as they don’t have to write
various codes for the same features. Furthermore, if any changes are
made in any particular part, it will not affect other parts of the
application.
Mobile app development:

 If you thought React is for web development only, you could not be more
wrong! Facebook has already upgraded the framework for developing
mobile native applications for both Android & iOS platforms.
It’s easy to learn:

 React, compared to other popular frontend frameworks like Angular &


Vue, is much easier to learn.
 In fact, it’s one of the main reasons why React gained so much attraction
in little time. It helps businesses quickly build their projects.
 You see, the harder it is to learn a particular technology or framework,
the more time it will take to begin the development process. And we, as
human beings, often tend to avoid things that are difficult to learn.
 But, since React is a simple framework that is easy to learn and get
started, businesses and big brands are more inclined towards using it.
It helps to build rich user interfaces:

 Today, the quality of the user interface in an application plays an


important role. If the user interface is poorly designed, then it lowers the
chances of an application to succeed.
 But, if an application has high-quality UI, then there are better chances
that your users will love to use the app.
 Therefore, building rich user interfaces is sort of necessary for an
application to survive and thrive.
 The good news is, React allows building such high-quality, rich user
interfaces through its declarative components, which brings us to our next
point.
It allows writing custom components:

 React comes with JSX, an optional syntax extension, which makes it


possible to write your own components.
 These components basically accept HTML quoting and also makes all
subcomponent rendering a delightful experience for developers.
 Though there have been many debates on the matter of JSX, but it has
already for writing custom components, building high-volume
applications, and converting HTML mockups into ReactElement trees.
It uplifts developers’ productivity:

 Frequent updates often turn into headaches when an app has a complex
logic and when a single modification in one component can dramatically
affect other components.
 But, to combat this problem, Facebook has amplified React with the
component reusability feature.
 Component reusability in React basically allows developers to redeploy
the same digital objects.
 The process is simple too! – developers, for example, can begin adding
simple components such as button, text fields, and checkbox and then
move them to wrapper components, which are ultimately moved forward
to the root component.
 This approach basically provides better code maintenance and growth as
each component in React has their own internal logic, which is easy to
manipulate and as a result, boosts the productivity of application
development.
It offers fast rendering:
 When you’re building a complex, high-load app, it becomes mandatory to
define the structure of the app in the beginning since it can impact the
performance of your app.
 In simple words, the DOM model is tree-structured. So, a minor
modification at a higher level layer can awfully impact the user interface
of an application. To solve this, Facebook has introduced a virtual DOM
feature.
 Virtual DOM, as the name suggests, is the virtual representation of DOM
that allows testing all changes to the virtual DOM first to calculate risks
with each modification.
 This approach, as a result, helps to maintain high app performance and
guarantees a better user experience.
It is SEO-friendly:

 For any online business, search engine optimization is the gateway to


success.
 According to Moz, the lower the page load time and the faster the
rendering speed, the higher an app will rank on Google.
 Thanks to the fast rendering, React, compared to other frameworks,
significantly reduces the page load time, which greatly helps businesses
in securing the first rank on Google Search Engine Result Page.
It comes with useful developer toolset:

 Learning emerging technologies and using them in real-life projects can


be both fun and beneficial, but only if they are used correctly.
 Facebook understands this and it’s for this reason they have added much
needed React dev tools and Chrome dev tools in their React JS
framework.
 These React tools basically help developers discover child and parent
components, observe component hierarchies, and inspect components’
present state and props.
Strong community support:

 Like Angular, React also has very strong community support, which is
one of the main reasons to adopt React JS in your project.
 Every day, a large number of individual React developers are
contributing towards making React a better frontend framework.
Currently, React JS has attained 136,079 stars on Github and 1,331
regular contributors.
 Not only that, but experts are also regularly uploading free React tutorials
on Youtube and writing in-depth React tutorial articles & blogs on the
internet. For instance, a simple “free React tutorial” search on Google
gives 13,00,00,000 results.
 Apart from this, React experts are also regularly solving doubts on QA
sites like Stack Overflow and Quora, meaning if you ever get stuck while
using React, you can always get reliable solutions given by experts.
It offer better code stability:

 React follows downward data flow to ensure that the parent structure
don’t get affected by any modifications in its child structure.
 So, whenever a developer makes changes in an object, he or she only
needs to modify its states and make proper amendments. This way only a
specific component will be updated.
 This data flow and structure, as a result, provide better code stability and
smooth performance of the application.
 It is used by many fortune 500 companies
Proficient Data binding:

 React uses one side data binding and flux which is an app designer that
handles data flow from a single point. Thus anybody has the ability to
track all the changes that are made to change specific portions of the data.
Extend your tools and capacities:

 The major benefit of React in a project, developers can write on


javascript and also on modem JSX. This approach will permit them to use
HTML inserts in code which enables an extensive chance for
restructuring and lifting complete productivity.
Testing and Functionality:

 React results not only in performance but is also highly testable


applications. It makes it easier to develop a clear design that is test-
friendly. They can be supervised from triggered outputs, functions,
events, etc. Test it before utilizing it and React JS makes it easy.
UI-focused designs:

 React JS provides potential to any UI layout. It permits significant data


changes to transform particular UI elements automatically. Due to this
latest feature, you do not require anything to update the UI.
It provides a unique abstraction layer
o One of the robust sides of React is that it offers a good abstraction
that means it does not reveal any complicated internals to the user.
Developers must be aware of a few basics and retain from
examining the internal functionalities.
Template designing made easy

 Template design saves hours of development time for amateur and


professional developers and permits them to write the code of an app
promptly after create-react-app completes setting up the development
environment.
****************************************************************
***** 38) How to decide which state management system to use in your
application

****************************************************************
***** 39) How u do error-handling in your project

****************************************************************
***** 40) Do u know unit-testing of components/Typescript

****************************************************************
*****

PWC
41) What are the advantages of using react over traditional JS websites?

****************************************************************
***** <epam>
42) Diff between Pure comp and normal comp

Regular component Pure component
A regular component does not A pure component on other hand
implement the implements shouldComponentUpdate
shouldComponentUpdate method, It with a shallow props and state
always returns true by default comparison.

****************************************************************
*****43) How to write a functional setState and what is the use of it
 https://www.freecodecamp.org/news/functional-setstate-is-the-future-of-
react-374f30401b6b/#:~:text=But%20now%20it%20does
%20%E2%80%94%20Functional,separately%20from%20the%20component
%20classes.%E2%80%9D
****************************************************************
*****44) Reducers?

****************************************************************
*****45) Difference between HTML and JSX?

****************************************************************
*****46) Stateful Component?
1) If the behaviour of a component is dependent on the state of the
component then it can be termed as stateful component.
2) These stateful components are always class components and have a state
that gets initialized in the `constructor`.
class App extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
render() {
// ...
}
}
React 16.8 Update:
Hooks let you use state and other React features without writing classes.
The Equivalent Functional Component
import React, {useState} from 'react';
const App = (props) => {
const [count, setCount] = useState(0);
return (
// JSX
)
}

****************************************************************
*****47) Functional Component?
 Function Components:
This is the simplest way to create a component. Those are pure JavaScript
functions that accept props object as the first parameter and return React
elements:
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
****************************************************************
*****48) Middleware that we r using? (epic)

****************************************************************
*****49) Which version of react you using?

****************************************************************
*****50) Changes in new version?

****************************************************************
*****51) Binding Arrow function?

****************************************************************
*****52) Webpack?

****************************************************************
*****53) Is Redux is Immutable?
 yes,
https://supertokens.com/blog/why-is-redux-state-immutable
****************************************************************
*****HCL:

54) Webworks?

****************************************************************
*****55) Why do we use react?

****************************************************************
*****56) Props is mutable or immutable? Is it a property or limitations and
why?

 Props are Immutable, yes it’s a property of props.


 The props of a react component is aimed to store values and functions
from it's parent component. It's just the pattern, props are immutable. If
you want to have a variable that would be mutable, then store it in the
state of the component. States are mutable.
****************************************************************
*****57) Constructor concept in react?

 The constructor is a method used to initialize an object's state in a class. It


automatically called during the creation of an object in a class.
 The concept of a constructor is the same in React.
 The constructor in a React component is called before the component is
mounted. When you implement the constructor for a React component,
you need to call super(props) method before any other statement. If you
do not call super(props) method, this.props will be undefined in the
constructor and can lead to bugs.
Syntax
Constructor(props){
super(props);
}

 In React, constructors are mainly used for two purposes:


 It used for initializing the local state of the component by assigning an
object to this.state.
 It used for binding event handler methods that occur in your
component.
Note:

 If you neither initialize state nor bind methods for your React
component, there is no need to implement a constructor for React
component.
 You cannot call setState() method directly in the constructor(). If the
component needs to use local state, you need directly to use 'this.state' to
assign the initial state in the constructor.
 The constructor only uses this.state to assign initial state, and all other
methods need to use setState() method.
****************************************************************
*****58) How do you route to different pages?

****************************************************************
*****59) Service / API calls?

****************************************************************
*****60) Redux Architecture?

Redux is a predictable state container for JavaScript applications. Redux


derives its ideas form the Flux architecture. It is basically a flux-like approach
to React applications.
Redux doesn’t necessarily have to be used with React only, you can use it for
AngularJS or JS too. But Redux works really well with React. Redux basically
provides a way for managing the store, unidirectional flow of data and much
more.
Flux architecture has multiple stores that are coordinated together by the
dispatcher and when there is a change all the stores need to update themselves.
But in Redux we have a single store. A single store that handles the entire
application. Any changes to the store are done through actions.
Now, in Redux we have some functions which are called reducer functions.
These functions basically take the previous state of the application and the
action specified and generate the next state for the application. In Redux,
changes in the state can only be made using these reducer functions. The
previous state still remains intact and a new state is generate originated from
the previous one.
Use of Redux:
 Time-travel debugging: In Redux you can always walk back and
check the changes you have made to the states. Easy logging of
states.
 Undo & Redo: While walking back you can always update/modify
the states as required by you.
 A Single Source: Redux has only one single store which makes it
really simple to understand.
 Reducer Functions: These functions generate a new state which is
originated from the previous state and hence it helps to link all the
states together
 Use of JS: In the reducer function along with the previous state, the
action is specified. Action comprises of a basic JavaScript Object
which is called as a Payload.
 immutability: When a new state is generated, the previous state
remains as is and is not modified in any way.
Redux gets integrated together with React using a model called react-redux.
Now for this integration, we use the react-redux package. But here we will be
covering only Redux. So as a first step, you need to install redux into your
React application:
****************************************************************
*****61) Why can’t we update store directly?

****************************************************************
*****62) Do’s and don’ts in react? (Repeated)
 Refer question no 10
****************************************************************
*****63) Middleware?
 Middleware is a software that acts as an intermediary between two
applications or services to facilitate their communication.
****************************************************************
*****64) Diff forEach and Map() method?

 The main difference between map and forEach is that the map method
returns a new array by applying the callback function on each element of
an array, while the forEach method doesn’t return anything.
 You can use the forEach method to mutate the source array, but this isn't
really the way it's meant to be used. Instead, it's great for when you need
to do some action with each element of the array.
 On the other hand, the map method is used for creating a new array, and
thus, it’s chainable. You can call a number of map operations one after
the other.
 The forEach method doesn’t return anything, so you can’t chain it with
any other methods—it’s not chainable.
****************************************************************
*****65) useMemo() vs useContext() vs useCallback()

****************************************************************
*****66) How to pass data from child to parent component?


Parent.js
import Child from ‘./Child’
function App(){
function getData(){
console.log(data)
}
return(
<>
<Child getData={getData} />
</>
)
}
Export default Parent
Child.js
function Child(props){
const [name, setName] =useState(“ ”)
handleSumbit =(e)=>{
e.preventDefault()
props.getData(name)
}
return (
<>
<form onSubmit={handleSubmit}>
<input type=”text”
onChange={(e)=>{setName(e.target.value} } />
</form>
</>
)
}
Export default Child
****************************************************************
*****67) How to improve application performance?
 https://www.codementor.io/blog/react-optimization-5wiwjnf9hj
****************************************************************
*****68) Differentiate context Api and Redux?
 You can use Context in your application directly and is going to be great for
passing down data to deeply nested components which what it was designed for.

Whereas **Redux** is much more powerful and provides a large number of


features that the Context API doesn't provide. Also, React Redux uses context
internally but it doesn't expose this fact in the public API.
****************************************************************
***** GlobalLogic
69) Drawback of using react? (repeating)
 1. React is just a view library, not a full framework.
2. There is a learning curve for beginners who are new to web development.
3. Integrating React into a traditional MVC framework requires some
additional configuration.
4. The code complexity increases with inline templating and JSX.
5. Too many smaller components leading to over engineering or boilerplate.
****************************************************************
*****70) What do you mean by functional setState?
 https://www.freecodecamp.org/news/functional-setstate-is-the-future-of-
react-374f30401b6b/#:~:text=But%20now%20it%20does
%20%E2%80%94%20Functional,separately%20from%20the%20component
%20classes.%E2%80%9D
****************************************************************
*****71) What is Code splitting? How do you perform code splitting in react?
 Code-Splitting is a feature supported by bundlers like Webpack and
Browserify which can create multiple bundles that can be dynamically loaded at
runtime. The react project supports code splitting via dynamic import() feature.
For example, in the below code snippets, it will make moduleA.js and all its
unique dependencies as a separate chunk that only loads after the user clicks the
'Load' button.
moduleA.js
const moduleA = 'Hello';
export { moduleA };
App.js
import React, { Component } from 'react';
class App extends Component {
handleClick = () => {
import('./moduleA')
. then(({ moduleA }) => {
// Use moduleA
})
.catch(err => {
// Handle failure
});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
}
}
export default App;
****************************************************************
*****72) What happens if we call setState in render() (repeated)
 In constructor , we should avoid using setState() because this is the only
place we directly assign the initial state to this. state . Also, we cannot directly
put it in render() either since changing state each time triggers re-rendering
which calls setState() again. This will result in an infinite loop
****************************************************************
*****publicis Sapient
73) What is react? How it different from angular?

****************************************************************
*****74) What are diff ways you make an api call in react
 1. The Fetch API
Fetch API is built into most modern browsers on the window object
(window.fetch), and enables us to easily make HTTP requests.
The following code snippets show a simple example of Fetch API in practice:
import {useEffect} from "react";
const fetchUsers = () => {
// Where we're fetching data from
return fetch("http://www.abc.cd/test")
// We get the API response and receive data in JSON format
.then((response) => response.json())
.then((data) => console.log(data))
.catch ((error) => console.error(error));}
The only goal of this function is to access the data and convert the response into
JSON using the response.json() method. Here, the JSON() method is used to get
the response object stored in the data and update the users’ state in our
application.
Fetch is promise-based, which means we can also catch errors using the .catch()
method. Any encountered error is used as a value to update our error’s state.
Now, adding to that, we will make this request, within the useEffect() hook,
with an empty dependencies array as the second argument. This is done so that
our request is only made once and is not dependent on any other data.
Here is an example how to use it in the useEffect() hook:
import {useEffect} from "react";
useEffect(() => {
fetchData()
}, []);
Isn’t this handy? Let’s see what the other methods do.
2. Axios library
Axios is a Promise-based HTTP client for JavaScript that can be used in your
front-end application and Node.js backend.
When using Axios, it’s easy to send asynchronous HTTP requests to REST
endpoints and perform CRUD operations.
In this example, we first have to install Axios using npm or yarn. Then, we will
add it as an import to our parent component.
npm install axios
The following code snippets show an example of how to use Axios:
import axios from "axios"
const fetchData = () => {
return axios.get("http://www.abc.cd/test")
.then((response) => console.log(response.data));
}
Similar to the Fetch API, Axios also returns a promise. However, in Axios, it
always returns a JSON response. The coding part is similar to the Fetch API,
except that it has shorter steps and better error handling.
Check out the official documentation for more information.
3. async/await syntax
async/await is a relatively new way to synchronously write asynchronous code.
When the async keyword is place before a function, it has two effects:
Makes it always return a promise.
Allows await to be used within it.
The await keyword before a promise makes JavaScript wait until that promise
settles, and then:
If it’s an error, the exception is generated.
Otherwise, it returns the result.
Take a look at the following code snippets:
async function fetchData() {
try {
const result = await axios.get("http://www.abc.cd/test")
console.log(result.data));
} catch (error) {
console.error(error);
}
}
When we use useEffect(), the effect function cannot be made an async function.
For that, we can create a separate async function in our component that we can
synchronously call within useEffect and fetch our data accordingly.
4. React-query library
React-query is a great library that solves the problem of managing server state
and caching in applications.
"It makes fetching, caching, synchronizing, and updating server state in your
React applications a breeze.”
Firstly, let’s install the required package:
npm install react-query react-query-devtools
Note: React-query also has its own dev tools that help us to visualize the inner
workings of React-query.
React-query gives us a cache that you can see below through the React Query
Devtools. This cache enables us to easily manage the requests we have made
according to the key-value we specify for each request.
import React from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider, useQuery } from "react-query";
import { ReactQueryDevtools } from "react-query/devtools";
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<FetchData />
</QueryClientProvider>
);
}

function FetchData() {
const { data } = useQuery("UserData", () =>
fetch("http://www.abc.cd/test").then((res) => res.json())
);
return (
<div>
// data you want to show
<ReactQueryDevtools initialIsOpen />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In short, we need to tell the library where we need to fetch the data and it will
handle caching, background updates, and refresh data without any extra code or
configuration.
It also provides some hooks or events for mutation, queries to handle errors, and
other states of side effects that remove the need for useState() and useEffect()
hooks and replaces them with a few lines of React-query logic.
****************************************************************
*****75) Explain total react flow & why it is called single page application
with one way data binding?

****************************************************************
*****76) What is shadow DOM? How it is different from virtual
 The Shadow DOM is a browser technology designed primarily for
scoping variables and CSS in web components.
 The Virtual DOM is a concept implemented by libraries in JavaScript on
top of browser APIs.
****************************************************************
*****77) What is context api can we have multiple providers for diff context
we make?

****************************************************************
*****78) What are render props?
 In react it is possible to use props where value is a function to control what is
actually render by a component.
Definition: The term “render props” refers to a technique for sharing code
between react components using a props whose value is a function.
Example1:
//App.js
<User render={(isLoggedIn)=> (isLoggedIn ? ‘krunal’: ‘guest’ ) } />
//User.js
Class User extends Component{
render(){
return <div> {this.props.render(true)} </div>
}
}
export default User

Example2:
//App.js
<Counter
render={(count, incrementCount) => (
<ClickCounter count={count} incrementCount={ incrementCount } />
)}
/>
<Counter
render={(count, incrementCount) => (
<HoverCounter count={count} incrementCount={ incrementCount } />
)}
/>
//Counter.js
Class Counter extends Component{
constructor(props){
super(props);
this.state={
count: 0
}
}
incrementCount =()=>{
this.setState((prevState)=>{
return { count:prevState.count + 1}
})
}
render(){
return(
<div>{this.props.render(this.state.count,
this.incrementCount)}</div>
)
}
}
export default Counter
//ClickCounter.js
Class ClickCounter extends Component{
render(){
const {count, incrementCount} =this.state;
return(
<button onClick={incrementCount}> Clicked {count} Times
</button>
)
}
}
export default ClickCounter
//HoverCounter.js
Class HoverCounter extends Component{
render(){
const {count, incrementCount} =this.state;
return(
<h1 onMouseOver={incrementCount}> Clicked {count} Times
</h1>
)
}
}
export default HoverCounter
****************************************************************
*****79) Write ur own memorization function

let sum =0;
const calc=(n)=>{
for(let i =0; i<= n; i++){
sum+=i;
}
return sum
}
// const cal=calc(5)
// console.time()
// console.log(cal)
// console.timeEnd()
const memoize =(func)=>{
let cache={}
return function(...args){
let n = args[0]
if(n in cache){
console.log("cache", cache)
return cache[n]
}
else{
console.log('calculating firsttime')
let result= func(n)
cache[n] = result
return result
}
}
}
console.time()
const efficient= memoize(calc)
console.log(efficient(5))
console.timeEnd()
console.time()
console.log(efficient(5))
console.timeEnd()
****************************************************************
*****80) Make a custom input hook that is reusable?

****************************************************************
*****81) What is compound component pattern


****************************************************************
*****82) Quest on react router

****************************************************************
*****83) React testing library

****************************************************************
*****84) Typescript /Webpack

****************************************************************
*****85) Diff bet SSG and SSR

****************************************************************
*****86) What is next js /Gatsby & how it is useful as compared to react?

****************************************************************
*****87) What are service workers & explain use case

****************************************************************
*****88) What is tree shaking/babel/prototype?

****************************************************************
*****What is the diff between virtual dom and real dom?

****************************************************************
*****89) Difference between component and container?
 https://www.cronj.com/blog/difference-container-component-react-js/
****************************************************************
*****90) How do you update the state of a component?
 https://www.geeksforgeeks.org/how-to-update-the-state-of-a-component-in-
reactjs/
****************************************************************
*****91. a) Should we update state directly?
 If you try to update the state directly then it won't re-render the component.
//Wrong
this.state.message = 'Hello world'
Instead use `setState()` method. It schedules an update to a component's state
object. When state changes, the component responds by re-rendering.
//Correct
this.setState({ message: 'Hello World' })
Note: You can directly assign to the state object either in constructor or using
latest javascript's class field declaration syntax.

****************************************************************
*****
91.b ) What will happen if we call setState inside componentDidUpdate?

 componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
 You may call setState() immediately in componentDidUpdate() but note
that it must be wrapped in a condition like in the example above, or you'll
cause an infinite loop. It would also cause an extra re-rendering which,
while not visible to the user, can affect the component performance.
****************************************************************
*****92) What is lifting the state up in react?
1) When several components need to share the same changing data then it is
recommended to lift the shared state up to their closest common ancestor.
2) That means if two child components share the same data from its parent,
then move the state to parent instead of maintaining local state in both of
the child components.

****************************************************************
*****93) What are the diff way to style a react component?
1)CSS Stylesheet
2)Inline Styling
3) CSS Modules
4)CSS in JS Library(styled component)

 CSS Stylesheet
// Stylesheet.js
function Stylesheet(props){
let className = props.primary ? ‘primary’: ‘’
return (
<div>
<h3 className={className} >stylesheet</h3>
</div>
)
}
export default Stylesheet
//App.js
render(){
return(
<div>
<Stylesheet primary={true}/>
</div>
)
}
//myStyles.css
.primary{
color : orange;
}
.font-xl{
font-size: 60px;
}
// Using template literals
return (
<div>
<h3 className={`${className} font-xl`}
</div>
)

 Inline styling
 In react inline styles are not specific as a string instead they are specified
with an object whose key is the camelCase version of the styling value is
a string
const heading ={
font-size: ‘50px’,
color: ‘green’
}
function Inline(){
return (
<div>
<h4 style={heading}>Inline</h4>
</div>
)
}
export default Inline

 Css Module
//appStyle.css
.error{
color: red;
}
//appStyles.module.css
success{
color: green;
}
//App.js
import ‘./appStyles.css”
import styles from ‘appStyles.module.css’
function App(){
return (
<div>
<h4 className=”error”>error </h4>
<h4 className=”{styles.success}>Success</h4>
</div>
)
}
export default App
****************************************************************
*****94) What is prop drilling in React?
 Prop Drilling is the process by which you pass data from one component
of the React Component tree to another by going through other
components that do not need the data but only help in passing it around.

****************************************************************
*****95) What is strict mode in react?
 `React.StrictMode` is a useful component for highlighting potential
problems in an application. Just like `<Fragment>`, `<StrictMode>` does not
render any extra DOM elements. It activates additional checks and warnings for
its descendants. These checks apply for *development mode* only.
import React from 'react'
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Header />
</div>
)
}
In the example above, the *strict mode* checks apply to `<ComponentOne>`
and `<ComponentTwo>` components only.
The <StrictMode> will be helpful in the below cases
1. Identifying components with **unsafe lifecycle methods**.
2. Warning about **legacy string ref** API usage.
3. Detecting unexpected **side effects**.
4. Detecting **legacy context** API.
5. Warning about deprecated findDOMNode usage

****************************************************************
*****96) How to perform automatic redirect after login?

****************************************************************
*****97) Diff react hooks and classes

****************************************************************
*****98 .a) What are semantics events in react?

****************************************************************
*****
98 .b) What are synthetic events in react?
1) SyntheticEvent is a cross-browser wrapper around the browser's native
event.
2) Its API is same as the browser's native event, including
`stopPropagation()` and `preventDefault()`, except the events work
identically across all browsers.

****************************************************************
*****99) What is react fiber and its goals
1) Fiber is the new reconciliation engine or reimplementation of core
algorithm in React v16.
2) The goal of React Fiber is to increase its suitability for areas like
animation, layout, gestures, ability to pause, abort, or reuse work and
assign priority to different types of updates; and new concurrency
primitives.
Its main goals are:
1. Ability to split interruptible work in chunks.
2. Ability to prioritize, rebase and reuse work in progress.
3. Ability to yield back and forth between parents and children to support
layout in React.
4. Ability to return multiple elements from render().
5. Better support for error boundaries.
****************************************************************
*****100) What is diff between react and reactDom?
React ReactDOM
The react package holds the react The react-dom package as the name
source for components, state, props implies is the glue between React and
and all the code that is react. the DOM. Often, you will only use it
for one single thing: mounting your
application to the index.html file with
ReactDOM.render().
React components are such a great react-dom is used only in web apps.
way to organize UI that it has now
spread to mobile to react is used in
web and in mobile.
The reason React and ReactDOM were split into two libraries was due to the
arrival of React Native (A react platform for mobile development).
****************************************************************
*****101) What are core principles of redux?
 Redux follows three fundamental principles:
1. Single source of truth:
The state of your whole application is stored in an object tree within a single
store. The single state tree makes it easier to keep track of changes over time
and debug or inspect the application.
2. State is read-only:
The only way to change the state is to emit an action, an object describing what
happened. This ensures that neither the views nor the network callbacks will
ever write directly to the state.
3. Changes are made with pure functions:
To specify how the state tree is transformed by actions, you write reducers.
Reducers are just pure functions that take the previous state and an action as
parameters, and return the next state.
****************************************************************
*****102) mapStateToProps vs mapDispatchToProps?
  `mapStateToProps()` is a utility which helps your component get
updated state (which is updated by some other components):
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
 mapDispatchToProps() is a utility which will help your component to fire
an action event (dispatching action which may cause change of
application state):
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
 It is recommended to always use the “object shorthand” form for the
`mapDispatchToProps`.
 Redux wraps it in another function that looks like (…args) =>
dispatch(onTodoClick(…args)), and pass that wrapper function as a prop
to your component.
const mapDispatchToProps = ({
onTodoClick
})
****************************************************************
*****103) Diff between redux-saga and redux-thunk?

****************************************************************
*****104) What is flux?
Flux Architecture:
Flux is AN architecture that Facebook uses internally when operating with
React.
It is not a framework or a library.
It is merely a replacement quite an architecture that enhances React and also
the idea of unidirectional data flow.
Redux is a predictable state container for JavaScript apps. Redux is a state-
management tool that is mostly used to React. Now speaking in terms of
React, simple applications have some components and the main component
which acts as the leader for the state of our application. Any changes made are
reflected back to the main component which then modifies the state.
But in reality, while creating a web application to solve a real-world problem,
we encounter hundreds of components that are organized into multiple groups
rather than one group with one main component. So they are organized into
multiple groups wherein each group has a main component managing the state
of that group.
Now, if you make changes to one of the components then one of the other
components may need re-rendering but if they don’t share a common main
component then passing of information between them can be difficult.
This is where we need an MVC (Model, View, Controller) model for the
application.
MVC model: An MVC model basically captures the entire state of the
application and any changes you want to make to the model from the view will
have to go through the controller to the model.

Need for Flux Architecture:

MVC faced certain issues due to which it couldn’t manage the application the
way we wanted it to. That’s where a new approach called Flux architecture
originated from the MVC model was designed. This approach was basically
designed to organize your code in a simpler web. The problems that with
MVC encountered was the fact that the updates, lead to a cascading flow of
updates within the models, and this becomes a tangled web, which makes the
application really complex.
The flux architecture, however, provides a unidirectional flow where a central
unit for the entire application is called the store. In Flux architecture, you can
have multiple stores. A store basically acts as a storehouse for the application
state. So, you can only modify the state of your application by requesting the
store.
The dispatcher becomes a controlling unit for serializing any actions that are
requested for changing the store. The store can be subscribed by views, be it
React views or controller views.
The storehouse of the state is the main component that will get its state from
the store of the flux architecture. Now whenever a change is made, the
controller views go back are able to get the updated state.
And this, in turn, might result in re-rendering of some parts of your views or
some parts of your components within your application. So, this is what is
meant by the unidirectional flow of data which forms the basis for the Flux
architecture.
****************************************************************
*****105) Diff flex and redux?
 https://www.clariontech.com/blog/mvc-vs-flux-vs-redux-the-real-
differences#:~:text=The%20primary%20difference%20of%20Flux,one
%20region%20of%20the%20app.
****************************************************************
*****
****************************************************************
*****

How You can pass data from child component to parent? Write code

****************************************************************
*****Make a timer component that auto decreases by 1 in every 1sec

****************************************************************
*****Make a small form component with name and password With
validation

****************************************************************
*****Create react app which change default displayed text to my name
onClick(simple one)

****************************************************************
*****Jenkins?

****************************************************************
*****Build Process?

****************************************************************
*****Do you know GraphQL?

****************************************************************
*****Tell me about your project that you currently working?

****************************************************************
*****How you fit within the team according to you

****************************************************************
*****Project structure?

****************************************************************
*****Can u tell me how you plan the design architecture?

****************************************************************
*****How does you folder structure looks like -show

****************************************************************
*****How do you handle pressure when working with multiple project

****************************************************************
*****How do u rate ur self in JS? Explain your role in your current project

****************************************************************
*****Did u worked directly with client

****************************************************************
*****Can u tell me how u plan design architecture

****************************************************************
*****Did you follow agile /Scrum method?

****************************************************************
*****How the total workflow of your application works right from pushing the
code to repository

****************************************************************
*****Do you know component level testing?

****************************************************************
*****Do you have any idea about CI/CD?

Javascript Interview Questions

1. Why do we need currying in JS? Explain with example.


 Currying is a functional programming concept where a function with multiple
arguments is transformed into a sequence of functions, each taking a single
argument. The purpose of currying in JavaScript is to create more flexible and
reusable functions. It allows you to partially apply arguments to a function,
creating a new function with some arguments already set.
 Here's an explanation of why currying is useful in JavaScript, along with an
example:
1. Partial Application:
 Currying allows you to partially apply arguments to a function, creating a new
function that "remembers" those arguments. This can be useful in scenarios
where you want to reuse a function with some fixed values.
2. Flexibility and Composition:
 Curried functions are more flexible and can be easily composed with other
functions. You can build more complex functions by combining simpler ones.
// Without Currying
function add(a, b, c) {
return a + b + c;
}
const result1 = add(1, 2, 3);
console.log(result1); // Output: 6
// With Currying
function curryAdd(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
const curriedAdd = curryAdd(1)(2)(3);
console.log(curriedAdd); // Output: 6
// Partial Application using Currying
const addWith2 = curryAdd(2);
const result2 = addWith2(3)(4);
console.log(result2); // Output: 9
In this example:
 The add function is a regular function that takes three arguments.
 The curryAdd function is a curried version of add. It returns a series of
functions that take one argument each.
 Partial application is demonstrated by creating a new function addWith2 with
the first argument set to 2. You can then use this partially applied function to
add 2 to any other two numbers.
 Currying allows you to create more modular and reusable functions. It plays
well with functional programming principles and enhances code readability and
maintainability in certain scenarios.
*********************************************************************
2. Explain Array prototyping, Generators?

In JavaScript, arrays have a prototype object, and the Array.prototype contains
a set of methods that can be used on all arrays. These methods provide a way to
perform common operations on arrays, such as iterating over elements,
filtering, mapping, reducing, and more.
Here are some common methods available in Array.prototype:
Iteration Methods:
1. forEach(callback): Executes a provided function once for each array
element.
2. map(callback): Creates a new array with the results of calling a provided
function on every element.
3. filter(callback): Creates a new array with all elements that pass the test
implemented by the provided function.
4.find(callback): Returns the first element in the array that satisfies the
provided testing function.
5. some(callback): Checks if at least one element in the array satisfies the
provided testing function.
6. every(callback): Checks if all elements in the array satisfy the provided
testing function.
Reduction Methods:
1. reduce(callback, initialValue): Applies a function against an accumulator
and each element in the array (from left to right) to reduce it to a single value.
2. reduceRight(callback, initialValue): Similar to reduce, but processes the
array from right to left.
Transformation Methods:
1. concat(array): Returns a new array that combines the elements of the original
array with elements from other arrays.
2. slice(start, end): Returns a shallow copy of a portion of an array.
3. splice(start, deleteCount, item1, item2, ...): Changes the contents of an array
by removing or replacing existing elements and/or adding new elements.
Search and Position Methods:
indexOf(searchElement, fromIndex): Returns the first index at which a given
element can be found in the array, or -1 if it is not present.
lastIndexOf(searchElement, fromIndex): Returns the last index at which a
given element can be found in the array, or -1 if it is not present.
includes(searchElement, fromIndex): Determines whether the array includes a
certain element.
These methods make working with arrays in JavaScript more convenient and
expressive.
Generators:
Generators are a special type of function in JavaScript that allows you to
pause and resume the execution of a function. They are created using
function* syntax.
 Key features of generators:
Pausing Execution:
Generators can be paused using the yield keyword, allowing the function to
yield control back to the calling code.
Resumable Execution:
Generators can be resumed, picking up from where they were paused, using the
next() method on the generator object.
Iterable Protocol:
Generators automatically implement the iterable protocol, so they can be used
in for...of loops and with other iterable features.
Infinite Sequences:
Generators are often used to create infinite sequences or lazy evaluation of
values, generating values on-demand.
Here's a simple example of a generator function:
function* countUpTo(limit) {
let count = 0;
while (count < limit) {
yield count;
count++;
}
}
const generator = countUpTo(5);
console.log(generator.next().value); // Output: 0
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3
console.log(generator.next().value); // Output: 4
console.log(generator.next().value); // Output: undefined
In this example, the generator function countUpTo yields numbers starting
from 0 up to the specified limit. The next() method is used to iterate over the
values yielded by the generator.
Generators provide a powerful and flexible way to work with sequences,
asynchronous operations, and other scenarios where pausing and resuming
execution is beneficial.
*********************************************************************
3. Function Closure and bind method difference?
Function closure and the bind method in JavaScript are related concepts that
involve managing the scope and context of functions, but they serve different
purposes.

Function Closure:
Definition:
A closure is created when a function is defined inside another function,
and the inner function has access to the outer function's variables and
parameters even after the outer function has finished execution. The inner
function "closes over" the outer function's scope.
Example:
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const closureExample = outerFunction(5);
console.log(closureExample(3)); // Output: 8
In this example, innerFunction is a closure because it has access to the x
variable from its containing scope (outerFunction), even though outerFunction
has completed its execution.
Bind Method:
Definition:
The bind method is a built-in method available on every function in
JavaScript. It creates a new function that, when called, has its this
keyword set to a specific value, and optionally, a specified sequence of
arguments is pre-appended to the arguments passed to the new function.
Example:
const obj = { value: 42 };
function printValue() {
console.log(this.value);
}
const boundFunction = printValue.bind(obj);
boundFunction(); // Output: 42
In this example, boundFunction is created by binding the printValue function to
the obj object. When boundFunction is called, this inside printValue refers to
obj, and it logs the value of obj.
Key Differences:
Purpose:
Closure: Deals with scope and variable access, allowing inner functions to
retain access to outer function variables even after the outer function has
completed execution.
Bind Method: Primarily used to set the this value for a function and optionally
pre-define arguments.
Syntax:
Closure: Involves defining a function within another function.
Bind Method: Involves calling the bind method on a function.
Execution Context:
Closure: The inner function retains access to the scope in which it was created.
Bind Method: Sets the this value for a function when it is called.
Return Value:
Closure: The inner function itself is returned.
Bind Method: Returns a new function with the specified this value and
optionally pre-defined arguments.
In summary, function closure is related to managing scope and variable access,
while the bind method is focused on setting the this value for a function and
optionally pre-defining arguments. Both concepts are important in JavaScript
for handling different aspects of function behavior.
*********************************************************************
How Authentication works in JWT?
JWT (JSON Web Token) is a compact, URL-safe means of representing
claims to be transferred between two parties. Authentication with JWT
involves generating a token on the server side, sending it to the client, and then
having the client include the token in subsequent requests to authenticate itself.
Here's an overview of how authentication works with JWT:
User Authentication:
When a user logs in, the server authenticates the user's credentials (username
and password).
Once authenticated, the server generates a JWT containing information about
the user (claims) and signs it using a secret key known only to the server.
Token Creation (Server Side):
The server creates a JWT with a header, payload, and signature.
The header typically includes the algorithm used for signing (e.g., HMAC
SHA256).
The payload contains the claims or information about the user, such as user ID,
username, and expiration time.
The server then signs the token with its secret key to produce the signature.
Token Issuance (Server Side):
The server sends the generated JWT to the client in the response.
The client receives the JWT and stores it securely, typically in a browser's
localStorage or as an HTTP-only cookie.
Token Verification (Server Side):
For subsequent requests, the client includes the JWT in the request header.
The server receives the JWT and verifies its authenticity by checking the
signature using the secret key.
If the signature is valid, the server proceeds to extract and use the information
from the claims (e.g., user ID).
Token Expiration:
JWTs often include an expiration time (exp claim) to ensure that they are not
valid indefinitely.
The server checks the expiration time to determine if the token is still valid.
If the token is expired, the client needs to request a new token by re-
authenticating.
Token Renewal (Optional):
If the server supports token renewal or refresh, the client can request a new
token without requiring the user to re-enter credentials.
This involves using a refresh token or a similar mechanism.
Logging Out (Optional):
To log out, the client can discard the JWT or notify the server to invalidate the
token (if supported).
The use of JWTs simplifies authentication by allowing servers to issue
compact, stateless tokens that can be easily verified on subsequent requests. It
is important to secure the transmission of JWTs (e.g., use HTTPS) and store
them securely on the client side. Additionally, proper token validation and
authorization checks on the server side are crucial for a secure authentication
system.
*********************************************************************
how localStorage session Stoage, cookies work in term of storing token and is it
secure for authentication?
LocalStorage, SessionStorage, and Cookies are different mechanisms for
storing data on the client-side in a web browser. When it comes to storing
authentication tokens, each has its advantages and security considerations:
 1. LocalStorage:
How it works:
LocalStorage is a key-value storage mechanism that persists data across page
reloads and browser sessions. Data stored in LocalStorage is accessible by
JavaScript running in the same origin.
Token Storage: You can store authentication tokens in LocalStorage using
localStorage.setItem('token', 'yourToken').
Security Considerations:
Vulnerable to XSS (Cross-Site Scripting) attacks: If an attacker injects
malicious scripts into your web page, they can potentially access LocalStorage
data.
No automatic expiration: Tokens stored in LocalStorage do not automatically
expire, so you need additional logic to manage token expiration and renewal.
Same-origin policy: Data stored in LocalStorage is accessible only by scripts
from the same origin.
 2. SessionStorage:
How it works:
Similar to LocalStorage but with a shorter lifespan. SessionStorage is cleared
when the browser session ends (e.g., when the user closes the tab or browser).
Token Storage: You can store tokens using sessionStorage.setItem('token',
'yourToken').
Security Considerations:
Still vulnerable to XSS attacks during the session.
Useful when you need a short-lived storage solution, and data persistence is not
required across sessions.
3. Cookies:
How it works:
Cookies are small pieces of data sent by the server and stored on the client's
browser. They have options for expiration, domain, and path.
Token Storage: You can store tokens in cookies using the Set-Cookie HTTP
header on the server or via JavaScript (document.cookie = 'token=yourToken;
expires=...; path=/').
Security Considerations:
Vulnerable to CSRF (Cross-Site Request Forgery) attacks:
Cookies can be sent automatically with every request, potentially leading to
unintended actions if a user is tricked into making a request.
Can be marked as HttpOnly: Adding the HttpOnly flag prevents JavaScript
access, reducing XSS attack vectors.
Secure flag: You can set the "Secure" flag to ensure cookies are only sent over
HTTPS connections.
Security Considerations:
XSS Vulnerability:
LocalStorage and SessionStorage are susceptible to XSS attacks if proper
measures are not taken (e.g., input validation, output encoding).
CSRF Vulnerability:
Cookies are vulnerable to CSRF attacks. To mitigate this, use anti-CSRF
tokens and ensure sensitive actions require a secure, authenticated, and
authorized request.
Token Expiration:
Ensure tokens have proper expiration settings, especially when using
LocalStorage or SessionStorage, to minimize the risk of unauthorized access.
HttpOnly and Secure Flags:
When using cookies, consider setting the HttpOnly flag to prevent JavaScript
access and the Secure flag to ensure cookies are only transmitted over HTTPS.
Conclusion:
Each storage mechanism has its trade-offs in terms of security, convenience,
and use cases. The key is to understand the security implications and choose an
approach based on your application's requirements and threat model.
Combining secure storage practices with other security measures (e.g., HTTPS,
anti-CSRF tokens) enhances the overall security of token-based authentication.
*********************************************************************
how localstorage ,session storage and cookies work when browser window
closed or open in new window or if entire browser closed and again open it?
The behavior of LocalStorage, SessionStorage, and Cookies in terms of
persistence when a browser window is closed or opened in a new window, as
well as when the entire browser is closed and reopened, varies. Here's an
overview:
 LocalStorage:
Persistence:
When Browser Window is Closed:
Data persists between browser sessions.
When Opened in a New Window:
Data is accessible in the new window/tab if it's from the same origin.
When Entire Browser is Closed and Reopened:
Data persists.
 SessionStorage:
Persistence:
When Browser Window is Closed:
Data is cleared when the window/tab is closed.
When Opened in a New Window:
Data is not accessible in the new window/tab.
When Entire Browser is Closed and Reopened:
Data is cleared.
 Cookies:
Persistence:
When Browser Window is Closed:
Depends on the cookie's expiration settings. Persistent cookies will
survive, while session cookies will be deleted.
When Opened in a New Window:
Accessible in the new window/tab if the cookie is not session-based and
hasn't expired.
When Entire Browser is Closed and Reopened:
Persistent cookies persist, and session cookies are deleted.
Notes:
Local Storage and Cookies:
LocalStorage and Cookies are accessible across multiple browser
windows/tabs as long as they are from the same origin.
LocalStorage data persists even when the browser is closed and reopened.
Session Storage:
SessionStorage is scoped to the session and is limited to a single browser
window/tab. It is cleared when the window/tab is closed.
Cookies:
Cookie expiration settings determine whether a cookie persists beyond the
current session or browser window.
The HttpOnly flag prevents JavaScript access to cookies, enhancing security.
Cookies can be marked as "Secure" to ensure they are transmitted only over
HTTPS connections.
Practical Implications:
Use LocalStorage when you need persistent data across browser sessions.
Use SessionStorage when you need data scoped to a single session or browser
window.
Cookies provide a way to store data that persists across sessions, but be
mindful of security considerations and manage expiration settings accordingly.
Remember that the behavior might be influenced by browser settings, privacy
modes, and specific scenarios. It's crucial to test and consider your application's
requirements when choosing the appropriate storage mechanism.
*********************************************************************
Different types of object creation?
In JavaScript, there are several ways to create objects, each with its own syntax
and use cases. Here are different types of object creation in JavaScript:
 Object Literal:
The simplest way to create an object is by using an object literal.
const person = {
name: 'John',
age: 30,
sayHello: function() {
console.log('Hello!');
}
};
 Constructor Function:
You can create objects using constructor functions. These functions are called
with the new keyword.
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log('Hello!');
};
}
const john = new Person('John', 30);
 Object.create:
The Object.create() method creates a new object with the specified prototype
object.
const personPrototype = {
sayHello: function() {
console.log('Hello!');
}
};
const john = Object.create(personPrototype);
john.name = 'John';
john.age = 30;
 Class Syntax (ES6 and later):
With the introduction of classes in ECMAScript 2015 (ES6), you can use the
class syntax to define and create objects.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log('Hello!');
}
}
const john = new Person('John', 30);
 Factory Function:
Factory functions are functions that return objects.
function createPerson(name, age) {
return {
name,
age,
sayHello: function() {
console.log('Hello!');
}
};
}
const john = createPerson('John', 30);
 Singleton Pattern:
The Singleton pattern ensures that a class has only one instance and provides a
global point of access to it.
const singleton = (() => {
let instance;
function init() {
// private methods and properties
return {
// public methods and properties
};
}
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
const singletonInstance = singleton.getInstance();
 Object Constructor (new Object()):
You can use the Object constructor to create a new empty object.
const person = new Object();
person.name = 'John';
person.age = 30;
person.sayHello = function() {
console.log('Hello!');
};
These are some common ways to create objects in JavaScript. The choice of
method depends on the specific use case, requirements, and coding style
preferences.
*********************************************************************
Explain Hoisting ? Temporal dead zone?
 Hoisting is Phenomenon in js where you can access the variables and
functions even before initialization or without assigning any value in it.
Example:
getName()
console.log(x)
var x= 8;
function getName(){
console.log(“Hello world”)
}
O/P: Hello World
Undefined
*********************************************************************
Explain IIFE with example?
IIFE stands for Immediately Invoked Function Expression. It is a design pattern
in JavaScript where a function is defined and executed immediately after its
creation. The primary purpose of using an IIFE is to create a private scope for
variables, preventing them from polluting the global scope.
Here's an example of an IIFE:
(function() {
// IIFE body
var localVar = 'I am a local variable.';
console.log(localVar);
})();
In this example:
The function is defined within parentheses () to create an expression.
The entire expression is then immediately invoked with an additional set of
parentheses (function() { /* code */ })();.
The variables declared inside the IIFE are local to that function and do not
interfere with variables in the global scope.
IIFE can also be used to create modules, encapsulating functionality and
avoiding global namespace pollution. Here's an example:
var module = (function() {
// Private variables and functions
var privateVar = 'I am private.';
function privateFunction() {
console.log('This is a private function.');
}
// Public interface
return {
publicVar: 'I am public.',
publicFunction: function() {
console.log('This is a public function.');
}
};
})();
console.log(module.publicVar); // Output: I am public.
module.publicFunction(); // Output: This is a public function.
console.log(module.privateVar); // Output: undefined (private variable)
module.privateFunction(); // Output: TypeError (private function)
In this module example:
 The IIFE encapsulates private variables and functions.
 It returns an object with a public interface, exposing only what is intended to be
public.
 Outside the IIFE, you can access the public interface, but the private members
remain inaccessible.
 IIFE is a common pattern in JavaScript, especially in scenarios where you want
to create isolated scopes, avoid naming conflicts, and create modular code.
*********************************************************************
What is Object literals and JSON object?
 Object Literals:
An object literal is a way to define and create an object in JavaScript directly
within the code. It's a convenient syntax for creating objects without the need
for a constructor function. Object literals consist of key-value pairs enclosed in
curly braces {}.
Here's an example of an object literal:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
isStudent: false,
sayHello: function() {
console.log('Hello!');
}
};
In this example, person is an object literal with properties like firstName,
lastName, age, isStudent, and a method sayHello.
 JSON Object:
JSON (JavaScript Object Notation) is a data interchange format that is often
used for data exchange between a server and a web application. JSON objects
resemble JavaScript object literals, but there are some key differences:
Syntax:
JSON object keys must be enclosed in double quotes, while JavaScript object
literals allow both double and single quotes.
// JSON
{
"firstName": "John",
"lastName": "Doe",
"age": 30,
"isStudent": false
}
// JavaScript Object Literal
{
firstName: 'John',
lastName: 'Doe',
age: 30,
isStudent: false
}
String Values:
In JSON, string values must be enclosed in double quotes, whereas JavaScript
object literals allow both double and single quotes.
Methods:
JSON is a data interchange format and does not support functions or methods.
Therefore, methods cannot be included in a JSON object.
JSON is often used to transmit data between a server and a client or between
different systems. When parsing a JSON string in JavaScript, it is converted
into a JavaScript object.
Example of a JSON string:
{
"name": "John",
"age": 25,
"city": "New York"
}
To convert a JSON string to a JavaScript object, you can use JSON.parse():
const jsonString = '{"name":"John","age":25,"city":"New York"}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: John
Both object literals and JSON objects are crucial for working with data in
JavaScript, with object literals being used for in-memory object creation and
JSON for data interchange between systems.
*********************************************************************
First Class function?
 In programming language design, the term "first-class function" refers to a
function that has the following properties:
Assignable:
Functions can be assigned to variables or stored in data structures.
const add = function(a, b) {
return a + b;
};
const multiply = function(a, b) {
return a * b;
};
Passed as Arguments:
Functions can be passed as arguments to other functions.
function operate(func, a, b) {
return func(a, b);
}
console.log(operate(add, 5, 3)); // Output: 8
console.log(operate(multiply, 5, 3)); // Output: 15
Returned from Functions:
Functions can be returned as values from other functions.
function getOperation(type) {
if (type === 'add') {
return add;
} else {
return multiply;
}
}
const operation = getOperation('add');
console.log(operation(5, 3)); // Output: 8
Stored in Data Structures:
Functions can be stored in data structures like arrays or objects.
const functionArray = [add, multiply];
console.log(functionArray[0](5, 3)); // Output: 8
console.log(functionArray[1](5, 3)); // Output: 15
In a programming language that supports first-class functions, functions are
treated as first-class citizens, similar to other data types like numbers, strings,
and objects. JavaScript is an example of a language with first-class functions,
which contributes to its versatility and the ability to use functional
programming concepts.
The concept of first-class functions is fundamental to functional programming
paradigms, allowing for more flexible and expressive programming styles. It
enables features like higher-order functions, closures, and functional
composition.

*********************************************************************
Error Page Creation?(Error Boundary IN React)
 Creating error pages in a React application involves handling errors and
rendering a dedicated component when an error occurs. React provides an
Error Boundary concept to catch JavaScript errors anywhere in a
component tree and log those errors, display fallback UI, and prevent the
entire application from crashing.
Here's a step-by-step guide on creating an error page in React:
1. Create an Error Boundary Component:
Create a new component that will act as an error boundary. This component
will catch errors and display a fallback UI.
// ErrorBoundary.js
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return (
<div>
<h2>Oops! Something went wrong.</h2>
<p>Please try again later.</p>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
2. Use the Error Boundary Component:
Wrap the parts of your application where you want to handle errors with the
ErrorBoundary component.
// App.js
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
import MyComponent from './MyComponent';
function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}
export default App;
3. Create the Fallback UI:
Inside the ErrorBoundary component, create a fallback UI that will be
displayed when an error occurs.
4. Logging and Reporting:
In the componentDidCatch method of the ErrorBoundary, you can log the error
and error information. Additionally, you can integrate tools like Sentry or other
error tracking services for more advanced error reporting.
Note:
The componentDidCatch method only catches errors in components below it in
the component tree.
Error boundaries do not catch errors in event handlers or during the initial
render of a component.
It's recommended to use error boundaries primarily for catching unexpected
errors, not for handling expected errors in regular application flow.
With this approach, when an error occurs within the ErrorBoundary
component's subtree, it will catch the error, update its state, and render the
fallback UI instead of crashing the entire application.
*********************************************************************
Scopes in JS?
JavaScript has two main types of scopes: global scope and local scope. The
scope determines the accessibility and visibility of variables in different parts
of your code. Understanding scopes is crucial for writing maintainable and
bug-free JavaScript code.
1. Global Scope:
Variables declared outside any function or block have global scope.
They can be accessed from anywhere in the code, including within functions
and blocks.
Global variables are properties of the window object in the browser.
// Global Scope
var globalVariable = 'I am global';
function exampleFunction() {
console.log(globalVariable); // Accessible from within a function
}
console.log(globalVariable); // Accessible globally
2. Local Scope:
Variables declared inside a function or block have local scope.
They are accessible only within the function or block where they are declared.
Each function or block creates its own scope.
// Local Scope (Function Scope)
function exampleFunction() {
var localVariable = 'I am local';
console.log(localVariable); // Accessible within the function
}
// console.log(localVariable); // Error: localVariable is not defined outside
the function
3. Block Scope (let and const):
=> Introduced with ES6, let and const have block-level scope.
=> Variables declared with let and const are limited to the block (enclosed by
{}) where they are defined.
// Block Scope (let and const)
if (true) {
let blockVariable = 'I am block-scoped';
const constantVariable = 'I am also block-scoped';
console.log(blockVariable); // Accessible within the block
console.log(constantVariable); // Accessible within the block
}
// console.log(blockVariable); // Error: blockVariable is not defined
outside the block
// console.log(constantVariable); // Error: constantVariable is not
defined outside the block
4. Function Parameters:
Parameters passed to a function act as local variables within the function.
They have scope limited to the function.
function exampleFunction(parameter) {
console.log(parameter); // Accessible within the function
}
// console.log(parameter); // Error: parameter is not defined outside the
function
5. Lexical Scope (Closure):
Lexical scope means that the inner function has access to variables in its outer
(enclosing) scope, even after the outer function has finished executing.
function outerFunction() {
var outerVariable = 'I am outer';
function innerFunction() {
console.log(outerVariable); // Accessible due to lexical scope
}
innerFunction();
}
outerFunction();
Understanding and managing scopes is crucial for avoiding naming conflicts,
maintaining code readability, and preventing unintended variable
modifications. It also plays a significant role in closures and how functions
remember their outer context.
*********************************************************************
Event loop – Task/ Microtask Queues?
In JavaScript, the event loop is a critical component of the runtime
environment that handles asynchronous operations and ensures smooth
execution of code. The event loop continuously checks the message queue for
events and processes them in a non-blocking manner.
Event Loop Phases:
Call Stack:
 The call stack is a data structure that keeps track of the function calls in the
program.
 When a function is called, it is pushed onto the call stack, and when the
function completes, it is popped off the stack.
Callback Queue (Task Queue):
 The callback queue, also known as the task queue, holds tasks or events to be
executed after the call stack is empty.
 Tasks in the callback queue are processed in the order they were added.
Microtask Queue:
 The microtask queue holds microtasks, which are tasks with higher priority
than regular tasks in the callback queue.
 Microtasks are processed before the callback queue tasks, even if the call stack
is not empty.
Execution Process:
Call Stack Execution:
 Code execution starts with functions being added to the call stack.
 Each function is executed until completion, and the stack is emptied.
Task Queue (Callback Queue):
 Asynchronous tasks, such as callbacks from setTimeout or DOM events, are
pushed to the callback queue when their conditions are met.
 These tasks wait for the call stack to be empty before being processed.
Microtask Queue:
 Microtasks, such as promises and mutation observers, are processed after the
current task in the call stack and before the next task in the callback queue.
 Microtasks are typically higher-priority tasks.
Example:
console.log('Start');
setTimeout(function() {
console.log('Timeout callback');
}, 0);
Promise.resolve().then(function() {
console.log('Promise resolved');
});
console.log('End');
In this example:
"Start" is logged to the console.
The setTimeout callback and the Promise callback are added to the task and
microtask queues, respectively.
"End" is logged to the console.
The microtask queue is checked, and "Promise resolved" is logged.
The task queue is checked, and "Timeout callback" is logged.
Key Points:
 Tasks in the callback queue are processed one at a time.
 Microtasks are processed until the microtask queue is empty before moving on
to the next task in the callback queue.
 The event loop ensures that the call stack is not blocked by long-running
synchronous operations, allowing asynchronous tasks to be executed in a non-
blocking manner.
 Understanding the event loop and task/microtask queues is crucial for writing
efficient and responsive asynchronous JavaScript code. It helps in managing
the flow of execution in a way that prevents blocking and ensures a smooth
user experience.
*********************************************************************
HTTP methods ….Explain?
HTTP (Hypertext Transfer Protocol) methods, also known as HTTP verbs, are
actions that indicate the desired operation to be performed on a resource
identified by a URI (Uniform Resource Identifier). Each HTTP method
corresponds to a specific operation, and the server processes the request
accordingly. Here are some common HTTP methods:
1. GET:
Purpose: Retrieve data from the server.
Safe: Yes (should not have side effects).
Idempotent: Yes (repeated requests have the same effect as a single request).
Example:
GET /api/users
2. POST:
Purpose: Submit data to be processed to a specified resource.
Safe: No (may have side effects).
Idempotent: No (repeated requests may have different effects).
Example:
POST /api/users
3. PUT:
Purpose: Update a resource or create it if it doesn't exist.
Safe: No (may have side effects).
Idempotent: Yes (repeated requests have the same effect as a single request).
Example:
PUT /api/users/123
4. PATCH:
Purpose: Partially update a resource.
Safe: No (may have side effects).
Idempotent: No (repeated requests may have different effects).
Example:
PATCH /api/users/123
5. DELETE:
Purpose: Delete a resource.
Safe: No (may have side effects).
Idempotent: Yes (repeated requests have the same effect as a single request).
Example:
DELETE /api/users/123
6. OPTIONS:
Purpose: Get information about the communication options available for a
resource.
Safe: Yes (should not have side effects).
Idempotent: Yes (repeated requests have the same effect as a single request).
Example:
OPTIONS /api/users
7. HEAD:
Purpose: Retrieve only the headers of a resource without the body.
Safe: Yes (should not have side effects).
Idempotent: Yes (repeated requests have the same effect as a single request).
Example:
HEAD /api/users/123
8. TRACE:
Purpose: Echoes the received request so that a client can see what changes or
additions have been made by intermediate servers.
Safe: Yes (should not have side effects).
Idempotent: Yes (repeated requests have the same effect as a single request).
Example:
TRACE /path/to/resource
9. CONNECT:
Purpose: Establish a network connection to a server over HTTP for tunneling
purposes (used in the creation of SSL/TLS encrypted tunnels).
Safe: No (may have side effects).
Idempotent: No (repeated requests may have different effects).
Example:
CONNECT www.example.com:443
These HTTP methods provide a standard way for clients to interact with
resources on the web. Each method has its specific use case and semantic
meaning, and their proper usage is essential for building robust and RESTful
web services.
*********************************************************************
Call, Apply, Bind Methods?
In JavaScript, call, apply, and bind are methods that allow you to manipulate
the context (the value of this) of a function. They are often used in situations
where you want to execute a function in a specific context or with a particular
set of arguments.
1. call Method:
The call method allows you to invoke a function with a specified this value and
individual arguments passed directly.
Syntax:
functionName.call(thisArg, arg1, arg2, ...);
Example:
const person = {
name: 'John',
sayHello: function(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
};
const anotherPerson = {
name: 'Alice'
};
person.sayHello.call(anotherPerson, 'Hi');
// Output: Hi, Alice!
2. apply Method:
The apply method is similar to call, but it takes an array-like object of
arguments instead of individual arguments.
Syntax:
functionName.apply(thisArg, [arg1, arg2, ...]);
Example:
const person = {
name: 'John',
sayHello: function(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
};
const anotherPerson = {
name: 'Alice'
};
person.sayHello.apply(anotherPerson, ['Hi']);
// Output: Hi, Alice!
3. bind Method:
The bind method creates a new function with a specified this value and initial
set of arguments. It doesn't invoke the function immediately but returns a new
function that can be invoked later.
Syntax:
const newFunction = functionName.bind(thisArg, arg1, arg2, ...);
Example:
const person = {
name: 'John',
sayHello: function(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
};
const anotherPerson = {
name: 'Alice'
};
const boundFunction = person.sayHello.bind(anotherPerson, 'Hi');
boundFunction();
// Output: Hi, Alice!
Key Differences:
call and apply invoke the function immediately, while bind creates a new
function with the specified context and arguments but doesn't invoke it right
away.
call takes individual arguments, apply takes an array-like object of arguments,
and bind takes both.
All three methods are used for setting the value of this in a function.
These methods are commonly used in scenarios where you want to control the
context of a function, especially when dealing with object-oriented
programming or when working with event handlers.
*********************************************************************
Arrow functions, anonymous functions, this keywords?
Arrow Functions:
Arrow functions were introduced in ECMAScript 6 (ES6) and provide a
concise syntax for writing functions. They have some key differences
compared to traditional function expressions:
// Traditional Function Expression
const add = function(a, b) {
return a + b;
};
// Arrow Function
const addArrow = (a, b) => a + b;
Key points:
Arrow functions do not have their own this. They inherit this from the
enclosing scope (lexical scoping).
They have a shorter syntax, especially when the function body is a single
expression.
Anonymous Functions:
Anonymous functions are functions without a name. Both traditional function
expressions and arrow functions can be anonymous:
// Anonymous Function Expression
const multiply = function(x, y) {
return x * y;
};
// Anonymous Arrow Function
const multiplyArrow = (x, y) => x * y;
Key points:
Anonymous functions are often used when the function is short-lived or when
it's passed as an argument to another function.
They can be assigned to variables or passed directly as arguments.
this Keyword:
Understanding the behavior of the this keyword is crucial when working with
functions, especially in the context of object-oriented programming and event
handlers.
In traditional functions:
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log(`Hello, ${this.name}!`);
};
}
const john = new Person('John');
john.sayHello(); // Output: Hello, John!
In arrow functions:
function Person(name) {
this.name = name;
this.sayHello = () => {
console.log(`Hello, ${this.name}!`);
};
}
const john = new Person('John');
john.sayHello(); // Output: Hello, John!
Key points:
Traditional functions have their own this context, which can be affected by
how the function is called.
Arrow functions inherit this from the enclosing scope, making them useful in
scenarios where you want to preserve the outer this context.
Considerations:
Arrow functions are often preferred for short and simple functions, especially
in contexts where preserving the outer this is desirable.
Traditional functions may be more suitable for certain scenarios, especially
when working with object-oriented programming constructs like prototypes.
*********************************************************************
ES-6 features?
ECMAScript 6 (ES6), also known as ECMAScript 2015, introduced several
significant features and enhancements to the JavaScript language. Here are
some key ES6 features:
1. Arrow Functions:
Arrow functions provide a concise syntax for writing functions, especially
useful for short, one-line functions.
// Traditional Function Expression
const add = function(a, b) {
return a + b;
};
// Arrow Function
const addArrow = (a, b) => a + b;
2. Template Literals:
Template literals allow for easy string interpolation and multiline strings.
const name = 'John';
const greeting = `Hello, ${name}!`;
3. Destructuring Assignment:
Destructuring allows you to extract values from arrays or objects and assign
them to variables in a concise way.
// Array Destructuring
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
// Object Destructuring
const person = { name: 'Alice', age: 30 };
const { name, age } = person;
4. Let and Const:
let and const provide block-scoped variable declarations, replacing var.
let count = 10;
count = 20;
const pi = 3.14;
5. Default Parameters:
Default parameters allow you to specify default values for function parameters.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('John'); // Output: Hello, John!
6. Rest and Spread Operators:
The rest operator (...) allows you to represent an indefinite number of
arguments as an array. The spread operator is used to expand elements of an
array or object.
// Rest Operator
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
// Spread Operator
const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5];
7. Classes:
ES6 introduced class syntax for creating constructor functions and managing
inheritance.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name}.`);
}
}
8. Modules:
Modules provide a standardized way to organize and reuse code.
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math';
console.log(add(2, 3)); // Output: 5
9. Promises:
Promises provide a cleaner syntax for handling asynchronous operations.
const fetchData = () => {
return new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve(data);
} else {
reject(error);
}
});
};
10. Map and Set:
ES6 introduced new data structures like Map and Set for more flexible and
efficient manipulation of collections.
// Map
const myMap = new Map();
myMap.set('key', 'value');
console.log(myMap.get('key')); // Output: value
// Set
const mySet = new Set([1, 2, 3, 3, 4]);
console.log([...mySet]); // Output: [1, 2, 3, 4]
These are just a few of the many features introduced in ES6. Subsequent
versions of ECMAScript have continued to build upon these features, bringing
additional improvements and enhancements to the JavaScript language.
*********************************************************************
Explain CORS , CSP, and XSS ?
CORS (Cross-Origin Resource Sharing):
CORS is a security feature implemented by web browsers to control cross-
origin HTTP requests. Cross-origin requests occur when a web page makes a
request to a different domain, protocol, or port than the one from which the
current page originated. CORS helps prevent unauthorized access to resources
and protects against potential security vulnerabilities.
Key points about CORS:
 Same-Origin Policy (SOP): By default, web browsers follow the Same-Origin
Policy, which restricts web pages from making requests to a different domain
than the one that served the web page.
 Cross-Origin Requests: If a web page needs to make requests to a different
origin, the server must include the appropriate CORS headers in its response.
These headers indicate which origins are allowed to access the resource.
CORS Headers:
Access-Control-Allow-Origin: Specifies which origins are allowed to access
the resource.
Access-Control-Allow-Methods: Specifies the HTTP methods (e.g., GET,
POST) allowed for the resource.
Access-Control-Allow-Headers: Specifies the HTTP headers allowed for the
resource.
Access-Control-Allow-Credentials: Indicates whether the browser should
include credentials (like cookies) when making the request.
Preflight Requests: For certain cross-origin requests, the browser may send a
preflight request (HTTP OPTIONS) to check whether the actual request is safe
to send.

CSP (Content Security Policy):


CSP is a security standard that helps prevent common types of code injection
attacks, such as Cross-Site Scripting (XSS). It allows web developers to declare
the sources from which a browser should load resources, reducing the risk of
malicious code execution.
Key points about CSP:
Policy Declaration: Developers can declare a Content Security Policy by
including the Content-Security-Policy HTTP header in the web server's
response.
Directives: CSP uses directives to specify which types of resources are
allowed. Common directives include:
default-src: Specifies the default source for resources.
script-src: Specifies the sources allowed for JavaScript.
style-src: Specifies the sources allowed for stylesheets.
img-src: Specifies the sources allowed for images.
Nonce and Hashes: CSP allows the use of nonces and hashes to whitelist
specific inline scripts and styles.
Reporting: CSP supports a reporting mechanism that allows developers to
receive reports about policy violations.
XSS (Cross-Site Scripting):
XSS is a type of security vulnerability where attackers inject malicious scripts
into web pages viewed by other users. The injected scripts can steal sensitive
information, manipulate content, or perform actions on behalf of the victim.
Common types of XSS:
Stored XSS: The injected script is permanently stored on the target server and
served to users visiting the affected page.
Reflected XSS: The injected script is embedded in a URL and reflected off a
web server to the victim.
DOM-based XSS: The attack occurs within the Document Object Model
(DOM) of the web page.
Preventing XSS:
Input Validation: Validate and sanitize user input on the server side to prevent
malicious content from being stored or executed.
Output Encoding: Encode user-generated content before rendering it in the
browser to prevent script execution.
Content Security Policy (CSP): Implementing a strong CSP can mitigate the
impact of XSS attacks by controlling the sources from which scripts can be
loaded.
By understanding and implementing these security measures, developers can
significantly reduce the risk of cross-origin security issues and protect web
applications from common vulnerabilities.
*********************************************************************
Array operations?
*********************************************************************
Shallow and Deep Copy ? Explain how will you create it?
*********************************************************************
Explain Event delegation in JS?
*********************************************************************
Diff between null and undefined
 https://www.geeksforgeeks.org/undefined-vs-null-in-javascript/
*********************************************************************
3) Evaluate type of null == undefined / null ===undefined
 https://www.geeksforgeeks.org/undefined-vs-null-in-javascript/
*********************************************************************
4) What is deep copy and shallow copy?
 https://www.freecodecamp.org/news/copying-stuff-in-javascript-how-to-
differentiate-between-deep-and-shallow-copies-b6d8c1ef09cd/#:~:text=A
%20deep%20copy%20means%20that,into%20how%20JavaScript%20stores
%20values.
****************************************************************
5) Diff between regular/normal function and arrow function
 https://betterprogramming.pub/difference-between-regular-functions-and-
arrow-functions-f65639aba256
***************************************************************
6) What is function currying? Explain with example
 Currying is advanced technique to working with functions.
Currying is transformation of functions that translates a function from callable
as f(a,b,c) into callable as f(a)(b)(c)
Currying doesn’t call functions; it just transforms it.
Currying can be perform in two ways.
1) Using bind()
2) Using closure
Using bind function
=> let multiply = function(x, y){
console.log(x * y)
}
=>let multiplyByTwo= multiply.bind(this, 2)
multiplyByTwo(4)
=> let multiplyByThree= multiply.bind (this, 3)
multiplyByTwo(6)
By Using closure
=> let multiply = function(x){
return function(y){
console.log(x * y)
}
}
=> let multiplyByTwo= multiply(this, 2)
multiplyByTwo(6)
****************************************************************
7) Difference between async and await /promise?
 https://www.geeksforgeeks.org/difference-between-promise-and-async-
await-in-node-js/
 https://www.loginradius.com/blog/engineering/callback-vs-promises-vs-
async-await/
****************************************************************
8) What is event delegation?
 Event delegation is a technique for listening to events where you delegate a
parent element as the listener for all of the events that happen inside it.
For example, if you wanted to detect field changes in inside a specific form, you
can use event delegation technique,
```javascript
var form = document.querySelector('#registration-form');
// Listen for changes to fields inside the form
form.addEventListener('input', function (event) {
// Log the field that was changed
console.log(event.target);
}, false);
*********************************************************************
10) Explain this keyword with arrow function and normal
 https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/
*********************************************************************
11) Event bubbling? How can we prevent it?
 Event bubbling is a type of event propagation where the event first triggers
on the innermost target element, and then successively triggers on the ancestors
(parents) of the target element in the same nesting hierarchy till it reaches the
outermost DOM element.
*********************************************************************
12) Diff between map, filter and reduce and foreach

*********************************************************************
13) What is diff between SPA vs MPA?
 https://medium.com/@NeotericEU/single-page-application-vs-multiple-
page-application-2591588efe58
 https://www.tekrevol.com/blogs/spa-vs-mpa/#:~:text=Differences
%20Between%20SPA%20and%20MPA,SPAs%20generally%20rely%20on
%20JavaScript.
*********************************************************************
accenture
14) What is JS? How do the browser understand your code?
*********************************************************************
15) Explain Event loop in JS?

*********************************************************************
Output coding 1+ “2”, […”Sandeep”], {}==={}/{}=={}

*********************************************************************
16) Can u iterate over an string

*********************************************************************
17) What is primitive and non-primitive data type in js?

 Data types that are known as primitive values in JavaScript are numbers,
strings, booleans, null, undefined. Objects such as functions and arrays
are referred to as non-primitive values.
 The fundamental difference between primitives and non-primitives is that
primitives are immutable and non-primitives are mutable.
 Primitives are known as being immutable data types because there is no
way to change a primitive value once it gets created.
 Primitives are compared by value. Two values are strictly equal if they
have the same value.
 Non-primitive values are mutable data types. The value of an object can
be changed after it gets created.
 Objects are not compared by value. This means that even if two objects
have the same properties and values, they are not strictly equal. Same
goes for arrays. Even if they have the same elements that are in the same
order, they are not strictly equal.
 Non-primitive values can also be referred to as reference types because
they are being compared by reference instead of value. Two objects are
only strictly equal if they refer to the same underlying object.
*********************************************************************
18) Typeof Array, type of null/ undefined

*********************************************************************
Infosys
19) Can u tell me diff between let, const and var?

*********************************************************************
20) Have u worked with promises? What is promises?

*********************************************************************
21) What is call apply and bind?

*********************************************************************
22) What is rest and spread operator? explain with example?

*********************************************************************
23) What is the slice and splice method in JS?

*********************************************************************
24) What is strict mode in JS?
 Strict Mode is a new feature in ECMAScript 5 that allows you to place a
program, or a function, in a “strict” operating context. This way it prevents
certain actions from being taken and throws more exceptions. The literal
expression `"use strict";` instructs the browser to use the javascript code in the
Strict mode.
*********************************************************************
LTI(L&T Infotech)
25) Http request life cycle

*********************************************************************
26) Diff between function expression and function declaration/function
statement?
Function expression: The function is first created and assigned to a variable
so that it can called by its variable name and useless until it is defined, it
cannot be executed otherwise it throws out “Uncaught Type Error”
Ex: var b = function (
Console.log(“b called”)
}
Function Declaration/Function Statement: The function is normally defined and
can be used later on.
function a (){
console.log(“a called”)
}
The Major difference between function statement and function expression is
hoisting.
=> We can called function a() before creating them in code , we can get o/p, but
in case of function b(), we will get uncaught type error.
=> In memory creation phase memory is created for function a() and it is assign
to that memory i.e. function a()
=> But in case of var b it will treat as an another variable it is assigned
undefined initially until code hits line where function is created.
*********************************************************************
27) Debouncing Code
 Most useful concepts for performance optimization by limiting function calls
on different events (typing events, scroll events, resize event, on other keyboard
/mouse events) .
<input type=”text” id=”input-event” placeholder=”type something” />
function debounce(func, delay){
let timeoutId;
return function(…args){
if(timeoutId){
clearTimeout(timeoutId)
}
timeoutId = setTimeout(){()=>{
func.call(this,…args)
},delay}
}
}
}
const myInput = document.getElementById(‘input-event’)
function findSuggestions(e){
console.log(‘Suggestions for”, e.target.value)
}
function decorator(findSuggestions, 300);
myInput.addEventListener(‘input’, decorator)
*********************************************************************
28) Can u tell me about pure function
 A Pure function is a function where the return value is only determined by
its arguments without any side effects. i.e, If you call a function with the same
arguments 'n' number of times and 'n' number of places in the application then it
will always return the same value.
Let's take an example to see the difference between pure and impure functions,
Syntax:
//Impure
let numberArray = [];
const impureAddNumber = number => numberArray.push(number);
//Pure
const pureAddNumber = number => argNumberArray =>
argNumberArray.concat([number]);
//Display the results
console.log (impureAddNumber(6)); // returns 1
console.log (numberArray); // returns [6]
console.log (pureAddNumber(7) (numberArray)); // returns [6, 7]
console.log (numberArray); // returns [6]
As per above code snippets, **Push** function is impure itself by altering the
array and returning an push number index which is independent of parameter
value. Whereas **Concat** on the other hand takes the array and concatenates
it with the other array producing a whole new array without side effects. Also,
the return value is a concatenation of the previous array.
Remember that Pure functions are important as they simplify unit testing
without any side effects and no need for dependency injection. They also avoid
tight coupling and make it harder to break your application by not having any
side effects. These principles are coming together with **Immutability**
concept of ES6 by giving preference to **const** over **let** usage.
*********************************************************************
29) What is callback hell
 Callback Hell is an anti-pattern with multiple nested callbacks which makes
code hard to read and debug when dealing with asynchronous logic. The
callback hell looks like below,
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
*********************************************************************
Why do u want to work with LTI even through you have good offers?
*********************************************************************
PWC
How much will you rate yourself in JS

*********************************************************************
30) Explain local storage, session storage and cookies +lifecycle

*********************************************************************
31) Have u used JWT? Advantages of it.

*********************************************************************
32) How you use JWT in your application? Explain

*********************************************************************
33) What are the security measures you take while building an application

*********************************************************************
Difference between BOM /DOM

*********************************************************************
34) Uses of promise.all, promise.any
 Promise.all is a promise that takes an array of promises as an input (an
iterable), and it gets resolved when all the promises get resolved or any one of
them gets rejected. For example, the syntax of promise.all method is below,
Promise.all([Promise1, Promise2, Promise3]) .then(result) =>
{ console.log(result) }) .catch(error => console.log(`Error in promises $
{error}`))
**Note:** Remember that the order of the promises(output the result) is
maintained as per input order
*********************************************************************
Center an div on screen (codesandbox)

*********************************************************************
35) Few guesses on console.log statements

*********************************************************************
EPAM
36) What is temporal dead zone
 console.log(a)
let a= 10;
var b= 100;
Temporal dead Zone is a time since when this let variable is hoisted and it is
initialize its value.
You can not access variable once it is in temporal dead zone.
You can access them once after you initialize them.
*********************************************************************
37) Explain how does browser understand JSX/JS
 1) Javascript XML(JSX) – Extension to javascript language syntax.
2) Write XML like code for elements and components.
3) JSX tags have a tag name, attributes, and children.
4) JSX makes your react code simple and elegant.
5) JSX ultimately trans piles to pure Javascript which is understood by
browser.
//With JSX

Import React from ‘react’


const MyComponent =()=>{
return (
<div className=”dummy-class”>
<h1>Hello Vishwas </h1>
</div>
)
}
//Without JSX

prreturn React.createElement(‘div’, {id:’hello’, className: ‘dummyClass’},


React.createElement(‘h1’,null, ‘Hello Vishwas’)
)
*********************************************************************
38) What is polyfill? Write a polyfill for forEach method

*********************************************************************
39) What do you mean by synchronous and asynchronous?

*********************************************************************
40) What is Object.freeze() does?

****************************************************************
41) a = [1,2,3,4,5], b = [6,7]
How can I insert array b in a at 3rd position?

const a=[1, 2, 3, 4, 5]
const b=[6,7]

a.splice(3, 0, ...b)
console.log(a)

const arr1 = ['a', 'd', 'e'];


const arr2 = ['b', 'c'];

arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']

console.log(arr1)

O/P: (7) [1, 2, 3, 6, 7, 4, 5]


(5) ['a', 'b', 'c', 'd', 'e']
****************************************************************
42) I have a nested object how you will clone it?

const circle = {
radius:1,
draw(){
console.log(‘draw’)
}
}

 const another ={}


for(let key in circle){
another[key] = circle[key] //Not recommended
}

1) Using Object.assign()
const another = Object.assign({},circle)
console.log(another)
2) Using Spread Operator
Const another = {…circle}
console.log(another)
****************************************************************
42) Closures?

43) for(var i=0; i<10; i++){
setTimeout( function (){
console.log(i)
},0)
}
console.log(i)

 O/P: 10
10,10,10,10,10,10,10,10,10,10
*********************************************************************
45) Custom Tags
*********************************************************************
*********************************************************************
45) What are functions called the first class citizen /first class functions in JS?
 It is the ability to use functions as values is known as first class function.
The ability of a function to use that value and pass that as an argument to the
another function and can be returned from function is called as First class
function.
Ex. var b = function(param1){
Return function xyz(){
}
}
Console.log(b())
Also
var b = function(param1){
console.log(param1)
}
function xyz(){
}
b(xyz)
=>Ability to use like values
=> used as value
=> can be passed as argument
=> can be executed inside a closured function
=> can be taken as return
*********************************************************************
46) What is coercion in JS?

*********************************************************************
47) What is pass by value /pass by reference
 Number/string/Boolean vs object/array
let a =20
let b= a
a = 10
console.log(a) //10
console.log(b) //20
This is nothing but passByValue
let array1 = [10,20,30]
let array2 = array1
array1.push(40)
console.log(array1) //[10,20,30,40]
console.log(array2) //[10,20,30,40]
This is nothing but passByReference
https://www.educative.io/answers/pass-by-value-vs-pass-by-reference
*********************************************************************
48) What is diff between await and yield keyword
 https://www.geeksforgeeks.org/what-is-the-difference-between-await-and-
yield-keywords-in-javascript/
*********************************************************************
What is difference between impure and pure pipe?

*********************************************************************
49) Write is difference between var and let and const?
Var Let Const
1) No Temporal dead 1) use Temporal dead 1) use Temporal dead
zone zone zone
2) can re-declared 2) can’t re-declare 2) can’t redeclare
3) can re-initialize 3) can re-initialize 3) can’t re-initialize
4) Store in global 4) store in separate 4) store in separate
Execution stack memory memory

*********************************************************************
50) Event bubbling & Event capturing?
 Event bubbling is a type of event propagation where the event first triggers
on the innermost target element, and then successively triggers on the ancestors
(parents) of the target element in the same nesting hierarchy till it reaches the
outermost DOM element.
 Event capturing is a type of event propagation where the event is first
captured by the outermost element, and then successively triggers on the
descendants (children) of the target element in the same nesting hierarchy till it
reaches the innermost DOM element.
*********************************************************************
51) Regular expressions?

*********************************************************************
52) Generators and iterators?

*********************************************************************
53) Array manipulations?

*********************************************************************
54) What is difference between variable hoisting and type casting?

*********************************************************************
55) Which data types supported by JavaScript?
 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
*********************************************************************
56) Explain observables?

*********************************************************************
57) Difference between promise and observables?

*********************************************************************
58) Sharables Modules?

*********************************************************************
59) Subject & Behavior subject?

*********************************************************************
60) How to use Map array without map ( )?

*********************************************************************
61) To empty an array?

*********************************************************************
62) How to convert an array to an object?

*********************************************************************
63) How to fulfill an array with data?

*********************************************************************
64) What is the difference between settimeout () & setInterval()

*********************************************************************
65) How to merge arrays?

*********************************************************************
66) How to find the intersection of two arrays?

*********************************************************************
67) How to remove falsie values from an array?

*********************************************************************
68) freeze() in Javascript?

*********************************************************************
69) You said inner function can access outer function variable? So if parent
component as nested child components, can it access the outer component
function or variables?

*********************************************************************
70) Immutable Function

*********************************************************************
71) What are the uses of Array.reverse()?

*********************************************************************

React And JS Coding Questions


1. Second Largest number from array without using Math.Sort function?
 Solution No -1
function secondLargest(arr) {
if (arr.length < 2) {
return "Array should have at least two elements";
}
let first = arr[0];
let second = arr[1];

if (second > first) {


[first, second] = [second, first];
}
for (let i = 2; i < arr.length; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] !== first) {
second = arr[i];
}
}
return second;
}
const numbers = [5, 2, 8, 9, 1, 7];
const result = secondLargest(numbers);
console.log("Second Largest Number:", result);

Solution No-2: (With Math. Function)


function findSecondLargest(arr) {
if (arr.length < 2) {
return "Array should have at least two elements.";
}

let firstLargest = Math.max(arr[0], arr[1]);


let secondLargest = Math.min(arr[0], arr[1]);

for (let i = 2; i < arr.length; i++) {


if (arr[i] > firstLargest) {
secondLargest = firstLargest;
firstLargest = arr[i];
} else if (arr[i] > secondLargest && arr[i] !== firstLargest) {
secondLargest = arr[i];
}
}

return secondLargest;
}

const numbers = [10, 5, 8, 12, 7, 3, 15];


const result = findSecondLargest(numbers);

console.log("Second Largest Number:", result);

Solution -3:(With Sort Method)


function findSecondLargest(arr) {
if (arr.length < 2) {
return "Array should have at least two elements.";
}

let [firstLargest, secondLargest] = arr.slice(0, 2).sort((a, b) => b - a);

for (let i = 2; i < arr.length; i++) {


if (arr[i] > firstLargest) {
secondLargest = firstLargest;
firstLargest = arr[i];
} else if (arr[i] > secondLargest && arr[i] !== firstLargest) {
secondLargest = arr[i];
}
}

return secondLargest;
}

const numbers = [10, 5, 8, 12, 7, 3, 15];


const result = findSecondLargest(numbers);

console.log("Second Largest Number:", result);


*********************************************************************
2. Write a program for form Validation without using any library?
 Solution -1:
import React, { useState } from 'react';
const FormValidation = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const [errors, setErrors] = useState({
name: '',
email: '',
password: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
// Validate the input on change
validateInput(name, value);
};
const validateInput = (name, value) => {
switch (name) {
case 'name':
setErrors({
...errors,
name: value.length < 3 ? 'Name must be at least 3 characters long' : '',
});
break;
case 'email':
// A simple email validation example
setErrors({
...errors,
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? '' : 'Invalid email
address',
});
break;
case 'password':
setErrors({
...errors,
password: value.length < 6 ? 'Password must be at least 6 characters long'
: '',
});
break;
default:
break;
}
};
const handleSubmit = (e) => {
e.preventDefault();
// Validate all fields before submitting
for (const [key, value] of Object.entries(formData)) {
validateInput(key, value);
}
// If there are no errors, submit the form
if (Object.values(errors).every((error) => error === '')) {
console.log('Form submitted:', formData);
} else {
console.log('Form contains errors. Please fix them.');
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input type="text" name="name" value={formData.name}
onChange={handleChange} />
<span>{errors.name}</span>
</div>
<div>
<label>Email:</label>
<input type="text" name="email" value={formData.email}
onChange={handleChange} />
<span>{errors.email}</span>
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={formData.password}
onChange={handleChange} />
<span>{errors.password}</span>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default FormValidation;
Solution -2:
import React, { useState } from 'react';

const FormValidation = () => {


const [formData, setFormData] = useState({
name: '',
email: '',
});
const [errors, setErrors] = useState({
name: '',
email: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
// Validate on change
validateField(name, value);
};
const handleSubmit = (e) => {
e.preventDefault();
// Validate all fields before submission
validateAllFields();
// Perform form submission logic if valid
if (isFormValid()) {
// Your form submission logic goes here
console.log('Form submitted:', formData);
}
};

const validateField = (fieldName, value) => {


let errorMessage = '';
switch (fieldName) {
case 'name':
errorMessage = value.trim() === '' ? 'Name is required' : '';
break;
case 'email':
errorMessage = !isValidEmail(value) ? 'Invalid email address' : '';
break;
default:
break;
}
setErrors({
...errors,
[fieldName]: errorMessage,
});
};
const validateAllFields = () => {
for (const fieldName in formData) {
validateField(fieldName, formData[fieldName]);
}
};
const isFormValid = () => {
return Object.values(errors).every((error) => error === '');
};
const isValidEmail = (email) => {
// A simple email validation regex
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
<span style={{ color: 'red' }}>{errors.name}</span>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="text"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
<span style={{ color: 'red' }}>{errors.email}</span>
</div>

<button type="submit">Submit</button>
</form>
);
};
export default FormValidation;
****************************************************************
3. Explain Rate limiting and write a small code to demonstrate?
 Rate limiting is a technique used to control the number of requests or
operations a user or client can perform within a specific time frame. It is
employed to prevent abuse, unauthorized access, or excessive use of
resources, ensuring fair usage and maintaining system stability.
 Rate limiting is often applied to APIs, web servers, or any service that
could be vulnerable to abuse or overload. It helps protect against various
issues, such as denial-of-service (DoS) attacks, brute force attacks, or
unintended high loads.
 In the context of a React application, rate limiting is typically
implemented on the server side, and the client (React) code can handle
responses or take appropriate actions based on the rate limit status.
Solution -1:
class RateLimiter {
constructor(limit, interval) {
this.limit = limit; // Maximum number of requests allowed in the interval
this.interval = interval; // Time interval in milliseconds
this.tokens = 0; // Available tokens in the bucket
this.lastRequestTime = Date.now(); // Timestamp of the last request
}
// Check if the request is allowed
allowRequest() {
const currentTime = Date.now();
const elapsedTime = currentTime - this.lastRequestTime;
// Refill the bucket based on elapsed time
this.tokens += (elapsedTime / this.interval) * this.limit;
this.tokens = Math.min(this.tokens, this.limit);
// Update the last request time
this.lastRequestTime = currentTime;
// Check if there are enough tokens to allow the request
if (this.tokens >= 1) {
this.tokens -= 1;
return true; // Request allowed
} else {
return false; // Request denied
}
}
}
// Example usage
const rateLimiter = new RateLimiter(5, 10000); // Allow 5 requests per 10 seconds
function makeRequest() {
if (rateLimiter.allowRequest()) {
console.log('Request allowed.');
// Your request logic goes here
} else {
console.log('Request denied. Rate limit exceeded.');
}
}
// Simulate multiple requests
makeRequest(); // Allowed
makeRequest(); // Allowed
makeRequest(); // Allowed
makeRequest(); // Allowed
makeRequest(); // Allowed
makeRequest(); // Denied (rate limit exceeded)
// Wait for the interval to pass
setTimeout(() => {
makeRequest(); // Allowed (interval has passed)
}, 10000);
Solution-2:
let lastRequestTime = 0;
const requestLimit = 3; // Maximum requests allowed within a certain time frame (in
seconds)
let requestCount = 0;

const fetchData = () => {


const currentTime = new Date().getTime() / 1000; // Convert milliseconds to seconds
// Check if the time since the last request is within the allowed time frame
if (currentTime - lastRequestTime < requestLimit) {
// Rate limit exceeded
console.log('Rate limit exceeded. Please try again later.');
} else {
// Allow the request
lastRequestTime = currentTime;
requestCount++;
console.log(`Fetching data (${requestCount} requests)`);
}
};

// Simulate making requests


fetchData(); // Request 1
fetchData(); // Request 2
fetchData(); // Request 3
fetchData(); // Rate limit exceeded (within the same time frame)
****************************************************************
4. Nested Array operation ? Flatten array?

1) Using Array.prototype.flat():
The flat() method is available in modern JavaScript environments and can be used
to flatten an array.
const nestedArray = [1, [2, [3, 4], 5]];
const flatArray = nestedArray.flat(Infinity);
console.log(flatArray);
The Infinity argument ensures deep flattening, regardless of the nesting level.
2) Using Array.prototype.reduce():
You can use the reduce() method to recursively flatten the array.
const nestedArray = [1, [2, [3, 4], 5]];
const flattenArray = (arr) =>
arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flattenArray(val) : val),
[]);
const flatArray = flattenArray(nestedArray);
console.log(flatArray);
This recursive approach works for any level of nesting.
3) Using Array.prototype.concat() with Spread Operator:
Concatenating arrays using the spread operator can also flatten the array.
const nestedArray = [1, [2, [3, 4], 5]];
const flatArray = [].concat(...nestedArray);
console.log(flatArray);
This approach works well for shallow nesting but may not handle deep nesting.
4) Using Recusrsion:
const flattenArray = (arr) => {
return arr.reduce((acc, val) => Array.isArray(val) ?
acc.concat(flattenArray(val)) : acc.concat(val), []);
};
const nestedArray = [1, [2, [3, 4], 5]];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
5) Using reduce() and concat():
Another approach is to use the reduce() method along with concat().
const nestedArray = [1, [2, [3, 4], 5]];
const flattenArray = (arr) => arr.reduce((acc, val) =>
acc.concat(Array.isArray(val) ? flattenArray(val) : val), []);
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
6) Using toString() and split():
A simple yet less preferred approach is to convert the array to a string and then
split it.
const nestedArray = [1, [2, [3, 4], 5]];
const flattenedArray = nestedArray.toString().split(',').map(Number);
console.log(flattenedArray);
Choose the method that best fits your use case and the JavaScript environment you
are working in. The flat() method is more concise and expressive, but if
compatibility is a concern, you may opt for the reduce() or spread operator
approach.
****************************************************************
5. Write a program to fetch Realtime data for a cricket/ football match?

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const LiveScores = () => {


const [cricketMatches, setCricketMatches] = useState([]);
const [footballMatches, setFootballMatches] = useState([]);

useEffect(() => {
const fetchData = async () => {
try {
const cricketResponse = await axios.get('http://localhost:3001/cricketMatches');
const footballResponse = await axios.get('http://localhost:3001/footballMatches');

setCricketMatches(cricketResponse.data);
setFootballMatches(footballResponse.data);
} catch (error) {
console.error('Error fetching live scores:', error.message);
}
};
fetchData();
}, []);

return (
<div>
<h2>Live Cricket Matches</h2>
<ul>
{cricketMatches.map((match) => (
<li key={match.id}>
{`${match.team1} vs ${match.team2}: ${match.score} (${match.status})`}
</li>
))}
</ul>
<h2>Live Football Matches</h2>
<ul>
{footballMatches.map((match) => (
<li key={match.id}>
{`${match.team1} vs ${match.team2}: ${match.score} (${match.status})`}
</li>
))}
</ul>
</div>
);
};
export default LiveScores;
****************************************************************
6. Implement a function that converts a javascript value into a JSON string?
Solution 1:
function customStringify(value) {
// Handle primitive types
if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
return String(value);
} else if (typeof value === 'string') {
return `"${value}"`;
}
// Handle arrays
if (Array.isArray(value)) {
const arrayString = value.map((item) => customStringify(item)).join(',');
return `[${arrayString}]`;
}
// Handle objects
if (typeof value === 'object') {
const objectString = Object.entries(value)
.map(([key, val]) => `"${key}":${customStringify(val)}`)
.join(',');

return `{${objectString}}`;
}
// Handle undefined and functions
return undefined;
}
const data = {
name: 'John',
age: 30,
city: 'New York',
isActive: true,
hobbies: ['reading', 'coding', 'traveling'],
address: {
street: '123 Main St',
zipCode: '10001',
},
};
// Convert JavaScript object to custom JSON string
const jsonString = customStringify(data);
console.log(jsonString);
Solution -2:
const data = {
name: 'John',
age: 30,
city: 'New York',
isActive: true,
hobbies: ['reading', 'coding', 'traveling'],
address: {
street: '123 Main St',
zipCode: '10001',
},
};
// Convert JavaScript object to JSON string
const jsonString = JSON.stringify(data);
console.log(jsonString);
****************************************************************
7. Implement a function that performs a deep copy of a value, but also
handle circular references?
Deep copying an object while handling circular references requires
special handling to avoid infinite loops. One way to achieve this is by
maintaining a map to track the objects that have already been copied
during the process. Here's an example of a function that performs a deep
copy with support for circular references:
function deepCopyWithCircularReferences(obj, copiesMap = new
WeakMap()) {
if (typeof obj !== 'object' || obj === null) {
return obj; // Return non-objects as is
}

// Check if the object has already been copied


if (copiesMap.has(obj)) {
return copiesMap.get(obj);
}

// Handle circular references


// Create a placeholder to prevent infinite loops
const placeholder = Array.isArray(obj) ? [] : {};
copiesMap.set(obj, placeholder);

// Copy each property recursively


for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const value = obj[key];
placeholder[key] = deepCopyWithCircularReferences(value,
copiesMap);
}
}

return placeholder;
}

// Example with circular reference


const originalObject = { prop1: 'value1' };
originalObject.circularRef = originalObject;

// Perform deep copy with circular reference handling


const copiedObject = deepCopyWithCircularReferences(originalObject);

console.log(copiedObject);
In this example:
The function deepCopyWithCircularReferences recursively copies each
property of the object.
It uses a copiesMap (a WeakMap) to keep track of objects that have
already been copied, preventing infinite loops for circular references.
If a circular reference is encountered, a placeholder is created in the
copied object, and the circular reference is resolved by referencing the
placeholder.
The Array.isArray check is used to handle arrays separately from other
objects.
Note: This implementation assumes that the circular references are within
the same object being copied. If circular references involve multiple
objects, additional logic may be needed. Also, keep in mind that this
approach may not work with objects that have prototype chains or non-
enumerable properties.
****************************************************************
8. Implement a function to construct a table of a contents from an HTML
documents?
Solution -1 Using JS:
function createTableOfContents() {
// Get all heading elements in the document
const headingElements = document.querySelectorAll('h1, h2, h3, h4, h5, h6');

// Create an unordered list to hold the table of contents


const tocList = document.createElement('ul');

// Iterate through each heading element


headingElements.forEach((heading) => {
// Create a list item for each heading
const listItem = document.createElement('li');

// Create a link to the heading's anchor


const link = document.createElement('a');
link.textContent = heading.textContent;
link.href = `#${heading.id || ''}`;

// Append the link to the list item


listItem.appendChild(link);

// Append the list item to the table of contents


tocList.appendChild(listItem);
});

// Append the table of contents to a specific container or the document body


const tocContainer = document.getElementById('table-of-contents');
if (tocContainer) {
tocContainer.appendChild(tocList);
} else {
document.body.appendChild(tocList);
}
}

// Call the function to create the table of contents


createTableOfContents();
Solution -2 Using React:
import React, { useEffect, useState } from 'react';
const TableOfContents = () => {
const [headings, setHeadings] = useState([]);
useEffect(() => {
// Function to fetch headings from the document
const fetchHeadings = () => {
const headingElements = document.querySelectorAll('h1, h2, h3, h4, h5,
h6');
const headingsArray = Array.from(headingElements).map((heading) => ({
text: heading.textContent,
id: heading.id,
tagName: heading.tagName.toLowerCase(),
}));
setHeadings(headingsArray);
};
// Call the function to fetch headings
fetchHeadings();
// Add event listener for hashchange to update the active heading based on
URL fragment
const handleHashChange = () => {
const activeHeading =
document.getElementById(window.location.hash.slice(1));
if (activeHeading) {
activeHeading.scrollIntoView({ behavior: 'smooth' });
}
};
window.addEventListener('hashchange', handleHashChange);
// Cleanup the event listener on component unmount
return () => {
window.removeEventListener('hashchange', handleHashChange);
};
}, []); // Empty dependency array ensures that this effect runs only once on
component mount
return (
<nav>
<h2>Table of Contents</h2>
<ul>
{headings.map((heading) => (
<li key={heading.id}>
<a href={`#${heading.id}`}>{heading.text}</a>
</li>
))}
</ul>
</nav>
);
};
export default TableOfContents;
*********************************************************************
9. Implement a function to filter rows of data matching a specified
requirement?
// Example data
const data = [
{ id: 1, name: 'John', age: 25, country: 'USA' },
{ id: 2, name: 'Alice', age: 30, country: 'Canada' },
{ id: 3, name: 'Bob', age: 28, country: 'UK' },
// ... more rows
];

// Function to filter rows based on a condition


function filterRows(data, condition) {
return data.filter(row => condition(row));
}

// Example usage: Filter rows where age is greater than 25


const filteredData = filterRows(data, row => row.age > 25);

console.log(filteredData);
*********************************************************************
10. Implement a function that performs insertion sort?
function insertionSort(arr) {
const length = arr.length;
for (let i = 1; i < length; i++) {
// Choose the current element to be inserted
const currentElement = arr[i];
// Start comparing with the elements before it
let j = i - 1;
// Move elements greater than the current element to the right
while (j >= 0 && arr[j] > currentElement) {
arr[j + 1] = arr[j];
j--;
}
// Insert the current element into its correct position
arr[j + 1] = currentElement;
}
return arr;
}
// Example usage:
const unsortedArray = [5, 2, 4, 3, 1];
const sortedArray = insertionSort(unsortedArray.slice());
console.log('Unsorted Array:', unsortedArray);
console.log('Sorted Array:', sortedArray);
****************************************************************
11. Implement a function that returns a memorized version of a function
which accepts any number of arguments?
function memoize(func) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log('Using memoized result for', args);
return cache.get(key);
}
const result = func(...args);
cache.set(key, result);
console.log('Calculating and caching result for', args);
return result;
};
}
// Example function to be memoized
function add(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
// Create a memoized version of the 'add' function
const memoizedAdd = memoize(add);
// Example usage:
console.log(memoizedAdd(1, 2, 3)); // Initial calculation and caching
console.log(memoizedAdd(1, 2, 3)); // Using memoized result
console.log(memoizedAdd(4, 5, 6)); // Initial calculation and caching
console.log(memoizedAdd(4, 5, 6)); // Using memoized result
*********************************************************************
12. Implement a function that acts like setInterval but returns a function to
cancel the interval?
Solution -1:
function customSetInterval(callback, interval) {
let intervalId = setInterval(callback, interval);
// Return a function to cancel the interval
const cancel = () => {
clearInterval(intervalId);
console.log('Interval canceled.');
};
return cancel;
}
// Example usage:
const cancelInterval = customSetInterval(() => {
console.log('Interval callback executed.');
}, 1000);
// Cancel the interval after 5 seconds
setTimeout(() => {
cancelInterval();
}, 5000);
Solution -2:
function customSetInterval(callback, interval) {
let intervalId;
const startInterval = () => {
intervalId = setInterval(callback, interval);
};
const cancelInterval = () => {
clearInterval(intervalId);
};
// Initial start
startInterval();

// Return the cancel function


return cancelInterval;
}
// Example usage:
const cancelInterval = customSetInterval(() => {
console.log('Interval callback');
}, 1000);
// Cancel the interval after 5 seconds
setTimeout(() => {
cancelInterval();
console.log('Interval canceled');
}, 5000);
*********************************************************************
13. Implement a function to highlight text if searched terms appears within
it?
import React, { useState } from 'react';
const TextHighlighter = () => {
const [searchTerm, setSearchTerm] = useState('');
const [text, setText] = useState('Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Integer nec odio. Praesent libero.');
const highlightText = () => {
if (!searchTerm) {
alert('Please enter a search term.');
return;
}

const highlightedText = text.replace(new RegExp(searchTerm, 'gi'), match


=> <span className="highlight">{match}</span>);
setText(highlightedText);
};

return (
<div>
<input
type="text"
placeholder="Enter search term"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={highlightText}>Highlight</button>

<p dangerouslySetInnerHTML={{ __html: text }}></p>

<style>
{`
.highlight {
background-color: yellow;
font-weight: bold;
}
`}
</style>
</div>
);
};
export default TextHighlighter;
*********************************************************************
14. Implement a function to recursively transform values.
function recursiveTransform(obj, transformer) {
if (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj)) {
// If the value is an array, recursively transform each element
return obj.map((element) => recursiveTransform(element, transformer));
} else {
// If the value is an object, recursively transform each property's value
const transformedObject = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
transformedObject[key] = recursiveTransform(obj[key], transformer);
}
}
return transformedObject;
}
} else {
// If the value is not an object, apply the transformation function
return transformer(obj);
}
}
// Example usage:
const data = {
name: 'John',
age: 30,
address: {
city: 'New York',
zipCode: '10001',
},
hobbies: ['reading', 'coding'],
};
// Define a simple transformer function (e.g., convert strings to uppercase)
const uppercaseTransformer = (value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
};
// Use the recursiveTransform function to apply the transformer
const transformedData = recursiveTransform(data, uppercaseTransformer);
console.log('Original Data:', data);
console.log('Transformed Data:', transformedData);
*********************************************************************
15. Implement a function that determines if two values are deep equal.
function deepEqual(value1, value2) {
// Base case: If both values are strictly equal, they are deeply equal
if (value1 === value2) {
return true;
}

// Check if both values are objects and not null


if (typeof value1 === 'object' && value1 !== null &&
typeof value2 === 'object' && value2 !== null) {

// Check if both objects have the same number of properties


const keys1 = Object.keys(value1);
const keys2 = Object.keys(value2);

if (keys1.length !== keys2.length) {


return false;
}
// Recursively compare each property
for (const key of keys1) {
if (!deepEqual(value1[key], value2[key])) {
return false;
}
}

// If all properties are deeply equal, the objects are deeply equal
return true;
}

// If values are not strictly equal and not both objects, they are not deeply
equal
return false;
}

// Example usage:
const obj1 = { name: 'John', age: 30, address: { city: 'New York' } };
const obj2 = { name: 'John', age: 30, address: { city: 'New York' } };
const obj3 = { name: 'Alice', age: 25, address: { city: 'London' } };

console.log(deepEqual(obj1, obj2)); // true


console.log(deepEqual(obj1, obj3)); // false
*********************************************************************
16.Implement a function that returns a new object after squashing the input
object?
Solution-1:
function squashObject(obj) {
const result = {};
function flattenHelper(currentObj, path = '') {
for (const key in currentObj) {
if (currentObj.hasOwnProperty(key)) {
const newPath = path ? `${path}.${key}` : key;
if (typeof currentObj[key] === 'object' && currentObj[key] !== null) {
// Recursively flatten nested objects
flattenHelper(currentObj[key], newPath);
} else {
// Assign the flattened property to the result object
result[newPath] = currentObj[key];
}
}
}
}
flattenHelper(obj);
return result;
}
// Example usage:
const nestedObject = {
person: {
name: {
first: 'John',
last: 'Doe'
},
age: 30,
address: {
city: 'New York',
zipCode: '10001'
}
},
hobbies: ['reading', 'coding']
};
const squashedObject = squashObject(nestedObject);
console.log('Original Object:', nestedObject);
console.log('Squashed Object:', squashedObject);
Solution-2:
function squashObject(obj) {
const result = {};
function squashHelper(source, target, currentKey = '') {
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
const newKey = currentKey ? `${currentKey}.${key}` : key;
if (typeof source[key] === 'object' && source[key] !== null) {
// Recursively squash nested objects
squashHelper(source[key], target, newKey);
} else {
// Assign non-object values directly
target[newKey] = source[key];
}
}
}
}
squashHelper(obj, result);
return result;
}
// Example usage:
const nestedObject = {
person: {
name: {
first: 'John',
last: 'Doe',
},
age: 30,
},
address: {
city: 'New York',
zipCode: '10001',
},
};
const squashedObject = squashObject(nestedObject);
console.log(squashedObject);
*********************************************************************
17. Implement a function that creates a resumable interval object?
function createResumableInterval(callback, interval) {
let timerId;
let paused = false;
function resume() {
if (!paused) return;
paused = false;
timerId = setInterval(callback, interval);
}
function pause() {
if (paused) return;
paused = true;
clearInterval(timerId);
}
// Initial start
resume();
// Return an object with resume and pause functions
return {
resume,
pause,
};
}
// Example usage:
const intervalObject = createResumableInterval(() => {
console.log('Interval callback');
}, 1000);
// Pause the interval after 3 seconds
setTimeout(() => {
intervalObject.pause();
console.log('Interval paused');
}, 3000);
// Resume the interval after 2 seconds
setTimeout(() => {
intervalObject.resume();
console.log('Interval resumed');
}, 5000);
*********************************************************************
18. Implement the functionality behavior of Promise.any()
****************************************************************
19. Implement the functionality behavior of Promise.allSettled()
****************************************************************
20. Implement a function that returns a memorized version of a function
which accepts a single arguments?
function memoize(func) {
const cache = new Map();
return function (arg) {
if (cache.has(arg)) {
console.log('Using memoized result for', arg);
return cache.get(arg);
}
const result = func(arg);
cache.set(arg, result);
console.log('Calculating and caching result for', arg);
return result;
};
}
// Example function to be memoized
function square(x) {
return x * x;
}
// Create a memoized version of the 'square' function
const memoizedSquare = memoize(square);
// Example usage:
console.log(memoizedSquare(5)); // Initial calculation and caching
console.log(memoizedSquare(5)); // Using memoized result
console.log(memoizedSquare(8)); // Initial calculation and caching
console.log(memoizedSquare(8)); // Using memoized result
*********************************************************************
21. Implement a function that formats a list of items into single readable
string.
Solution -1:
function formatList(items) {
if (!Array.isArray(items)) {
return 'Invalid input. Please provide an array of items.';
}
if (items.length === 0) {
return 'The list is empty.';
}
// Join the items with commas and add "and" before the last item
const formattedString = items.slice(0, -1).join(', ') + (items.length > 1 ? ' and ' : '') +
items.slice(-1);
return `The list contains: ${formattedString}.`;
}
// Example usage:
const fruits = ['apple', 'orange', 'banana'];
console.log(formatList(fruits));
const numbers = [1, 2, 3, 4, 5];
console.log(formatList(numbers));
const emptyList = [];
console.log(formatList(emptyList));
const notAnArray = 'not an array';
console.log(formatList(notAnArray));
Solution-2:
function formatList(items, conjunction = 'and') {
if (!items || items.length === 0) {
return '';
}
if (items.length === 1) {
return items[0].toString();
}
const lastItem = items.pop();
const formattedList = items.join(', ') + ` ${conjunction} ` + lastItem;
return formattedList;
}
// Example usage:
const fruits = ['Apple', 'Banana', 'Orange'];
const formattedFruits = formatList(fruits);
console.log('Formatted List:', formattedFruits);
*********************************************************************
22. Implement a function that convert javascript value into JSON string.
function convertToJsonString(value) {
try {
const jsonString = JSON.stringify(value);
return jsonString;
} catch (error) {
console.error('Error converting to JSON:', error.message);
return null;
}
}

// Example usage:
const data = {
name: 'John',
age: 30,
city: 'New York',
hobbies: ['reading', 'coding'],
};

const jsonString = convertToJsonString(data);


if (jsonString !== null) {
console.log('JSON String:', jsonString);
}
*********************************************************************
23. Implement a class that can subscribe to and emit events that trigger
attached callback function?
class EventEmitter {
constructor() {
this.events = {};
}
subscribe(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
emit(eventName, ...args) {
const eventCallbacks = this.events[eventName];
if (eventCallbacks) {
eventCallbacks.forEach(callback => callback(...args));
}
}
unsubscribe(eventName, callback) {
const eventCallbacks = this.events[eventName];
if (eventCallbacks) {
this.events[eventName] = eventCallbacks.filter(cb => cb !== callback);
}
}
}
// Example usage:
// Create an instance of EventEmitter
const eventEmitter = new EventEmitter();
// Subscribe to an event
const callback1 = data => console.log('Callback 1:', data);
const callback2 = data => console.log('Callback 2:', data);
eventEmitter.subscribe('exampleEvent', callback1);
eventEmitter.subscribe('exampleEvent', callback2);
// Emit the event
eventEmitter.emit('exampleEvent', 'Event data');
// Unsubscribe from the event
eventEmitter.unsubscribe('exampleEvent', callback1);
// Emit the event again
eventEmitter.emit('exampleEvent', 'Event data after unsubscribe');
*********************************************************************
24. Implement a debounce function that comes with cancel method to cancel
delayed invocations?
function debounce(func, delay) {
let timeoutId;
function debounced(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, delay);
}
debounced.cancel = () => {
clearTimeout(timeoutId);
};
return debounced;
}
// Example usage:
// Original function
function onInput(value) {
console.log('Input value:', value);
}
// Debounced version with a 500ms delay
const debouncedOnInput = debounce(onInput, 500);
// Simulating input events
debouncedOnInput('A');
debouncedOnInput('AB');
debouncedOnInput('ABC');
// Cancel the delayed invocation
debouncedOnInput.cancel();
// Simulate another input event (won't trigger the debounced function)
debouncedOnInput('ABCD');
*********************************************************************
25. Implement a function to merge rows data from same user?
function mergeRowsByUser(rows) {
const mergedData = {};

rows.forEach(row => {
const userId = row.userId;
if (!mergedData[userId]) {
// If user does not exist in mergedData, create a new entry
mergedData[userId] = { ...row };
} else {
// If user already exists, merge the data
mergedData[userId] = { ...mergedData[userId], ...row };
}
});
// Convert the merged data object back to an array of rows
const mergedRows = Object.values(mergedData);

return mergedRows;
}
// Example usage:
const rows = [
{ userId: 1, name: 'John', age: 30, city: 'New York' },
{ userId: 2, name: 'Alice', age: 25, city: 'London' },
{ userId: 1, hobbies: ['reading', 'coding'] },
{ userId: 3, name: 'Bob', age: 28, city: 'Paris' },
];
const mergedRows = mergeRowsByUser(rows);
console.log(mergedRows);
*********************************************************************
26. Implement a function that return an object with all falsie values
removed?
Solution-1:
function removeFalsyValues(obj) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key]) {
result[key] = obj[key];
}
}
return result;
}
// Example usage:
const inputObject = {
name: 'John',
age: 30,
city: '',
isActive: true,
hobbies: [],
};
const resultObject = removeFalsyValues(inputObject);
console.log(resultObject);
Solution-2:
function removeFalsyValues(obj) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key]) {
result[key] = obj[key];
}
}
return result;
}
// Example usage:
const inputObject = {
name: 'John',
age: 30,
address: null,
isActive: true,
hobbies: [],
role: undefined,
};
const filteredObject = removeFalsyValues(inputObject);
console.log(filteredObject);
*********************************************************************
27. Implement a function to resolve a given value to a Promise.
****************************************************************
28. Implement a Turtle class that moves a turtle on a 2D plane.
class Turtle {
constructor(x = 0, y = 0, direction = 'right') {
this.x = x;
this.y = y;
this.direction = direction;
}
move(distance) {
switch (this.direction) {
case 'up':
this.y += distance;
break;
case 'down':
this.y -= distance;
break;
case 'left':
this.x -= distance;
break;
case 'right':
this.x += distance;
break;
default:
console.error('Invalid direction');
}
}
turnLeft() {
switch (this.direction) {
case 'up':
this.direction = 'left';
break;
case 'down':
this.direction = 'right';
break;
case 'left':
this.direction = 'down';
break;
case 'right':
this.direction = 'up';
break;
default:
console.error('Invalid direction');
}
}

turnRight() {
switch (this.direction) {
case 'up':
this.direction = 'right';
break;
case 'down':
this.direction = 'left';
break;
case 'left':
this.direction = 'up';
break;
case 'right':
this.direction = 'down';
break;
default:
console.error('Invalid direction');
}
}
getPosition() {
return { x: this.x, y: this.y };
}
getDirection() {
return this.direction;
}
}
// Example usage:
const turtle = new Turtle();
console.log('Initial Position:', turtle.getPosition());
console.log('Initial Direction:', turtle.getDirection());
turtle.move(5);
console.log('Position after moving 5 units:', turtle.getPosition());
turtle.turnLeft();
turtle.move(3);
console.log('Position after turning left and moving 3 units:',
turtle.getPosition());
turtle.turnRight();
turtle.move(2);
console.log('Position after turning right and moving 2 units:',
turtle.getPosition());
*********************************************************************
29. Implement a function to execute N async tasks in series?
async function executeTasksInSeries(tasks) {
for (const task of tasks) {
await task();
}
}
// Example usage:
async function asyncTask1() {
console.log('Task 1 started');
// Simulate asynchronous operation (e.g., API call, setTimeout)
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Task 1 completed');
}
async function asyncTask2() {
console.log('Task 2 started');
await new Promise(resolve => setTimeout(resolve, 500));
console.log('Task 2 completed');
}
async function asyncTask3() {
console.log('Task 3 started');
await new Promise(resolve => setTimeout(resolve, 800));
console.log('Task 3 completed');
}
const tasksToExecute = [asyncTask1, asyncTask2, asyncTask3];
executeTasksInSeries(tasksToExecute);
*********************************************************************
30. Implement a promisify function that allows the original function to
override the return value?
function promisify(originalFunction) {
return function (...args) {
return new Promise((resolve, reject) => {
const originalReturnValue = originalFunction.apply(this, args);
if (originalReturnValue instanceof Promise) {
// If the original function already returns a promise, use it
originalReturnValue.then(resolve).catch(reject);
} else {
// If the original function returns a value, resolve with that value
resolve(originalReturnValue);
}
});
};
}
// Example usage:
function syncFunction(value) {
return value + 10;
}
function asyncFunction(value) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(value + 20);
}, 1000);
});
}
const promisifiedSyncFunction = promisify(syncFunction);
const promisifiedAsyncFunction = promisify(asyncFunction);
// Using the promisified functions
promisifiedSyncFunction(5)
.then(result => console.log('Promisified Sync Result:', result));
promisifiedAsyncFunction(10)
.then(result => console.log('Promisified Async Result:', result));
*********************************************************************
31. Implement a function to deserialize a JSON string.
function deserializeJson(jsonString) {
try {
const deserializedObject = JSON.parse(jsonString);
return deserializedObject;
} catch (error) {
console.error('Error deserializing JSON:', error.message);
return null;
}
}
// Example usage:
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const deserializedObject = deserializeJson(jsonString);
if (deserializedObject !== null) {
console.log('Deserialized Object:', deserializedObject);
}
*********************************************************************
32. Implement a function to convert all keys in an object to camel case?
function convertKeysToCamelCase(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
const camelCaseObject = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const camelCaseKey = key.replace(/_([a-z])/g, (_, letter) =>
letter.toUpperCase());
camelCaseObject[camelCaseKey] = convertKeysToCamelCase(obj[key]);
}
}
return camelCaseObject;
}
// Example usage:
const snakeCaseObject = {
first_name: 'John',
last_name: 'Doe',
address_info: {
city_name: 'New York',
postal_code: '10001',
},
};
const camelCaseObject = convertKeysToCamelCase(snakeCaseObject);
console.log('Original Object:', snakeCaseObject);
console.log('Camel Case Object:', camelCaseObject);
*********************************************************************

1) Write a program to check whether a string is palindrome or not?


 Example 1:
function checkPalindrome(string) {

// find the length of a string


const len = string.length;

// loop through half of the string


for (let i = 0; i < len / 2; i++) {

// check if first and last string are same


if (string[i] !== string[len - 1 - i]) {
return 'It is not a palindrome';
}
}
return 'It is a palindrome';
}

// take input
const string = prompt('Enter a string: ');

// call the function


const value = checkPalindrome(string);

console.log(value);
###############################################################
Example2:
function reverse( str )
{
// variable holds reverse string
let rev_str = "";
for(let i =str.length-1;i >= 0;i--)
{
rev_str+= str[i];
}
// return reverse string
return rev_str;
}

// function checking string is palindrome or not


function is_palindrome( str )
{
reverse_str = reverse(str);
// condition checking if reverse str is
// same as string it is palindrome
// else not a palindrome
if( reverse_str === str)
{
console.log("passed string is palindrome ");
}
else
{
console.log("passed string is not palindrome")
}
}
let test = "hellolleh";
is_palindrome(test);
###############################################################
Example3:
let checkPalindrome = (strn) => {
return strn === strn.split("").reverse().join("");
};

console.log("Is Palindrome? : " + checkPalindrome("noon"));


console.log("Is Palindrome?: " + checkPalindrome("apple"));
****************************************************************
***** 2) How do you find reverse a string without using any inbuild method?

Example 1:
function reverseString(str) {
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}
reverseString('hello');
Example 2:
function reverseString(str) {
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");
****************************************************************
***** 3) Write a JavaScript function that reverse a number?

Example:
function rev_num()
{
var num = prompt("Enter the number to be reveresed :", " ");
var n= num;
var rev = 0, rem;
while (n>0)
{
rem = n % 10;
rev = rev * 10 + rem ;
n = Math.floor(n/10);
}
document.write("The given number is : " +num+ " <br/> The reversed
number is : " +rev+ "\n");
}
****************************************************************
***** 4) Find the second largest element from an array in JavaScript?

Approach 1:
function findSecondLargest(a, n) {
/*First, sort the array and find the first_largest element present in the
array (at the last position).*/
a.sort();
/*Now for the second_largest element, we need to start from second last
element as the largest element is at last. */
let second_largest = 0;
/*If the last and second last element are equal then check the previous
one else return the second last element.*/
for (let i = n - 2; i >= 0; i--) {
if (a[i] != a[n - 1]) {
second_largest = a[i];
break;
}
}
return second_largest;
}
const a = [12, 35, 1, 10, 34, 1];
let n = a.length;
let answer = findSecondLargest(a, n);
console.log("The second largest element in the array is: " + answer);
################################################################
#####Approach 2:
function findSecondLargest(a, n) {
/*Let us assume that initially, the largest element (first_largest) present
in the array is Number.MIN_SAFE_INTEGER.*/
let first_largest = Number.MIN_SAFE_INTEGER;
/*The first loop will find the first_largest element present in the array.*/
for (let i = 0; i < n; i++) {
/*Update the value of first_largest if the current element is larger than
the first_largest value till now. */
if (first_largest < a[i]) {
first_largest = a[i];
}
}
/* Now find the largest element present in the array which is smaller
than the first_largest.
Initially, the second element present in the array is
Number.MIN_SAFE_INTEGER.*/
let second_largest = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
if (a[i] > second_largest && a[i] < first_largest) {
second_largest = a[i];
}
}
return second_largest;
}
const a = [12, 35, 1, 10, 34, 1];
let n = a.length;
let answer = findSecondLargest(a, n);
console.log("The second largest element in the array is: " + answer);
################################################################
#####Approach 3:
function findSecondLargest(a, n) {
/*Initialize the variable first_largest with the value 0 and second_largest
with the value -1. */
let first_largest = 0;
let second_largest = -1;
/*Now update the values of first_largest and second_largest in each
iteration as per the approach. */
for (let i = 0; i < n; i++) {
if (a[i] > a[first_largest]) {
second_largest = first_largest;
first_largest = i;
} else if (a[i] < a[first_largest]) {
if (second_largest == -1 || a[second_largest] < a[i]) second_largest = i;
}
}
return a[second_largest];
}
const a = [12, 35, 1, 10, 34, 1];
let n = a.length;
let answer = findSecondLargest(a, n);
console.log("The second largest element in the array is: " + answer);
****************************************************************
***** 5) Create a for loop that iterates up to 100 while outputting “Fizz” at
multiples of 3, “buzz” at multiples of 5 and “fizz buzz” at multiples of 3 and 5?
 for(var i =1; i<=100; i++){
if(i%3 === 0 && i%5 ===0){
console.log(“FizzBuzz”)
}
else if(i%3 === 0){
Console.log(“Fizz”)
}
else if(i%5 ===0){
console.log(“Buzz”)
}
else{
console.log(i)
}
}
****************************************************************
***** 6) Print Prime Numbers between 1 to 100 in JavaScript?

function isPrime(num) {
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
function display(n) {
var arr = [2];
for ( var i = 3; i < n; i+=2 ) {
if ( isPrime(i) ) {
arr.push(i);
}
}
console.log(arr); // use arr result on your own
}

display(100);
****************************************************************
***** 7) Print Fibonacci up to 100 in JavaScript?
9
****************************************************************
***** 8) How to add something in the beginning and end of an array?
to add at beginning use unshift() and at end push()
****************************************************************
***** 9) How to find duplicate elements from an array? (Repeated)

****************************************************************
***** 10) Remove adjacent duplicate characters from string? (Repeated)

****************************************************************
***** 11) Check a number is prime or not?

****************************************************************
***** 12) How to swap two variables in JavaScript?
 https://www.programiz.com/javascript/examples/swap-variables
****************************************************************
***** 13) Write a JavaScript function that checks whether a passed string is
palindrome or not? (Repeated)
 Same as question 1
****************************************************************
***** 14) Write a JavaScript function that check number is Armstrong or not?
 // program to check an Armstrong number of three digits

let sum = 0;
const number = prompt('Enter a three-digit positive integer: ');

// create a temporary variable


let temp = number;
while (temp > 0) {
// finding the one's digit
let remainder = temp % 10;

sum += remainder * remainder * remainder;

// removing last digit from the number


temp = parseInt(temp / 10); // convert float into integer
}
// check the condition
if (sum == number) {
console.log(`${number} is an Armstrong number`);
}
else {
console.log(`${number} is not an Armstrong number.`);
}

// program to check an Armstrong number of n digits


// take an input
const number = prompt("Enter a positive integer");
const numberOfDigits = number.length;
let sum = 0;

// create a temporary variable


let temp = number;

while (temp > 0) {

let remainder = temp % 10;

sum += remainder ** numberOfDigits;

// removing last digit from the number


temp = parseInt(temp / 10); // convert float into integer
}

if (sum == number) {
console.log(`${number} is an Armstrong number`);
}
else {
console.log(`${number} is not an Armstrong number.`);
}

****************************************************************
***** 15) Write a JavaScript function that find the Armstrong number of 3
digits?

function three_digit_armstrong_number()
{
for (var i = 1; i < 10; ++i)
{
for (var j = 0; j < 10; ++j)
{
for (var k = 0; k < 10; ++k)
{
var pow = (Math.pow(i,3) + Math.pow(j,3) + Math.pow(k,3));
var plus = (i * 100 + j * 10 + k);
if (pow == plus)
{
console.log(pow);
}
}
}
}
}
three_digit_armstrong_number();
****************************************************************
***** 16) Write a program to console all 2 digits twisted prime numbers in
JavaScript?

****************************************************************
***** 17) Write a program to find the min number of an array in JavaScript?

****************************************************************
*****
18) Will they both return same output? If not why?
function foo1(){
return {
bar: ‘hello’,
}
}
Function foo2(){
return
{
bar: ‘hello’
}
}
console.log(foo1()) //hello
console.log(foo2()) //undefined
****************************************************************
***** 19) once the below code is executed, tell me the order of number 1-4
logged in the console
function cb1(){ console.log(2) }
function cb2(){ console.log(3) }
function myTask(){console.log(‘task done’)}
const promise = newPromise({resolve,reject} =>{
resolve()
})
(function(){
console.log(1);
setTimeout(cb1, 1000);
promise.then(myTask);
setTimeout(cb2,0);
console.log(4);
})()
o/p:1,4, task done,3,2
****************************************************************
***** 20) Input SearchBoxKey, output searchBoxKey
****************************************************************
***** 21) Remove duplicate from array and count the number of duplicate?
 const numbers=[1,2,3,4,2,2,2,1,3,5,7,9,11,11,19,1];

const checkDuplicates=(item,index, arr)=>{


return arr.sort((a,b) => a-b).filter(x => x !== arr[index-1] && x ===item);
}
numbers.forEach(function(item, index, arr){
let check =checkDuplicates(item,index,arr);
if( check && check.length >0){
console.log(`Number is : ${item} & total count : ${check.length}`);

};
});

****************************************************************
***** 22) Write a sum method which will work properly ,when invoked using
either syntax below
console.log(sum(2, 3)) //output: 5
console.log(sum(2) (3)) //output: 5
 function sum(){
If (arguments.length == 2){
return arguments[0] + arguments[1]
} else{
return function (y){
return x + y
}
}
}
console.log(sum(2)(3)(9) //output: 14
 function sum(){
If (arguments.length == 2){
return arguments[0] + arguments[1]
} else{
return function (y){
return function (z){
return x + y + z;
}
}
}
}
****************************************************************
***** 23) What is the unsurely of using typeof bar ===”object” to determine if
bar is an object? How can we avoid this to make sure if bar is an object?

****************************************************************
***** 24) Sort an array /count duplicates in an array?
Approach 1: Set()
let arr = [1,3,3,4,4,6,5,6,4,5,3,4,6,2,1,21,2,3]
Ans:=> let newUniqueArr = […new Set(arr)]
Note: new Set(arr) is a Set containing all the values in arr, which duplicates
necessarily removed. Then spread operator just converts this back into an array.
################################################################
#####
Approach 1:
const fruits =
['Apple','Lemon','Grapes','Banana','Orange','Orange','Apple','Lemon']
const unique = […new Set(fruits)]
or
const unique = Array.from(new Set(fruits))
################################################################
#####
Approach 2: filter()
const unique = fruits.filter((value, index)=>{
return fruits.indexOf(value) === index
})
console.log(unique)
console.log(Array.prototype)

document.querySelector(‘#my-dropdown”).innerHTML =`
${unique.map(value => {
return `<option>${value}</option>`
})}
`;
################################################################
#####
Approach 3: forEach()
function uniqueElement(array){
const unique = []
array.forEach(value =>{
if(!unique.includes(value)){
unique.push(value)
}
})
return unique;
}
uniqueElement(fruits)
################################################################
#####
Approach 4: reduce()
function uniqueElement(array){
array.reduce((prev, current) =>{
console.log(prev,current)
if(!prev.includes(current)){
prev.push(value)
}
})
return prev;
}
const unique =uniqueElement(fruits)
unique()

****************************************************************
***** 25) Write a logic to count the maximum number of repeating characters
in a string

################################################################
#####
function maxCount(input) {
const {max, ...counts} = (input || "").split("").reduce(
(a, c) => {
a[c] = a[c] ? a[c] + 1 : 1;
a.max = a.max < a[c] ? a[c] : a.max;
return a;
},
{ max: 0 }
);

return Object.entries(counts).filter(([k, v]) => v === max);


}

maxCount('--aaaa1111--').join(' | ').replace(/,/g, ':');


****************************************************************
***** 26) Write a logic to move all 0’s to the end of an array

var moveZeroes = function(nums) {
let zeros = 0
for (let i = 0; i < nums.length; i++) {
let isZero = nums[i] === 0
if (isZero){
zeros++
nums.splice(i, 1)
i—
}
}
for (let i = 0; i < zeros; i++){
nums.push(0)
}
return nums
};
################################################################
####
var moveZeroes = function(nums) {
for (let i = nums.length - 1; i >= 0; i--) {
nums[i] === 0 && nums.splice(i, 1) && nums.push(0);
}
return nums
};

You might also like