React Interview Questions 2024
React Interview Questions 2024
React Interview Questions 2024
<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="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100">
<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>
****************************************************************
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>
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?
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.
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
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?
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.
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]);
// 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
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.
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
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.
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.
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’]
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.
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 · 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.
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() {
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?
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:
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:
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:
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:
****************************************************************
***** 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?
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?
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.
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.
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?
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.
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
a.splice(3, 0, ...b)
console.log(a)
arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']
console.log(arr1)
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()?
*********************************************************************
return secondLargest;
}
return secondLargest;
}
<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;
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
}
return placeholder;
}
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');
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 (
<div>
<input
type="text"
placeholder="Enter search term"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={highlightText}>Highlight</button>
<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;
}
// 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' } };
// Example usage:
const data = {
name: 'John',
age: 30,
city: 'New York',
hobbies: ['reading', 'coding'],
};
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);
*********************************************************************
// take input
const string = prompt('Enter a 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;
}
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: ');
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];
};
});
****************************************************************
***** 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 }
);