0% found this document useful (0 votes)
52 views

Impors

Prototypes are used for inheritance in JavaScript. A prototype is an object that is linked to a function, and when that function is used as a constructor (with new), the resulting object gets the prototype as a hidden property. Prototype chaining allows inheriting and sharing properties among objects. The slice() method returns a shallow copy of elements from the original array into a new array object, while splice() removes elements and/or adds new elements.

Uploaded by

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

Impors

Prototypes are used for inheritance in JavaScript. A prototype is an object that is linked to a function, and when that function is used as a constructor (with new), the resulting object gets the prototype as a hidden property. Prototype chaining allows inheriting and sharing properties among objects. The slice() method returns a shallow copy of elements from the original array into a new array object, while splice() removes elements and/or adds new elements.

Uploaded by

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

JAVASCRIPT INTERVIEW QUESTIONS?

what do you mean by prototype in Javascript?


A prototype is an object. When you declare a function, a prototype
is created and linked to that function.In javascript Prototypes are
the mechanism by which JavaScript objects inherit properties from
one another.
Example of Prototype :
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
const myFather = new Person("John", "Doe", 50);
const myMother = new Person("Sally", "Rally", 48);

what is protoType chaining?


Prototype chaining is used to build new types of objects based on
existing ones. It is similar to inheritance in a class based language.
The prototype on object instance is available through
Object.getPrototypeOf(object) or __proto__

Example of ProtoType Chaining :

what do you mean by call, apply and bind?


1) Call: The call() method invokes a function with a given this value
and arguments provided one by one or in listing manner.
2) Apply : Apply method Invokes the function with a given this value
and allows you to pass in arguments as an array.
3) Bind : returns a new function, allowing you to pass any number
of arguments in listing mannaer.

Example of call ,apply and bind

let userDetails={
name: "kanu",
age:"21"
}
let printDetails=function(designation,company){
console.log(this);
console.log("designation of employee"+designation);
console.log("company name of employee"+company);
}
printDetails.call(userDetails,"software Engineer","TCS");
printDetails.apply(userDetails,["software Testing","Infosys"]);
let printt=printDetails.bind(userDetails,"Manual
Tester","Cognizant");
printt();

what is JSON and its properties?


JSON is an acronym for JavaScript Object Notation, is an open
standard format, which is lightweight and text-based, easy to read
and write. It is a language-independent data format. It supports
almost every kind of language, framework, and library.

properties of JSON are following

1) The data is in name/value pairs


2) The data is separated by commas
3) Curly braces hold objects
4) Square brackets hold arrays

what are slice and splice method what are the difference between
them?

The slice() method returns the selected elements as a new array


object. It takes two parameter first parameter shows from which
position elements selected and second parameter show ending
position of an array. If you omit the second argument then it selects
till the end.

Example of slice

let myArray=[12,23,45,67,89]
let result=myArray.slice(1,4)
Output: [23,45,67]

The splice() method is used for either adds/removes items to/from


an array, and then returns the removed item. The first argument
specifies the array position for insertion or deletion whereas the
optional second argument indicates the number of elements to be
deleted.

Example of splice method

let myArray=[12,23,45,67,89]
remove 4 elements starting from index 1
let result=myArray.splice(1,4)
remove 4 elements starting from index 1 and add all new elemnts
let result=myArray.splice(1,4,12,44,55,66,78)

what is the difference between == and ===?


Double equals (==) is a comparison operator, which transforms the
operands having the same value before comparison.

=== (Triple equals) is a strict equality comparison operator in


JavaScript, which returns false for the values which are not of a
similar type. This operator performs type casting for equality. If we
compare 2 with “2” using ===, then it will return a false value.

what do you mean by arrow function?


Arrow functions is also called fat arrow function. They are called
the shorter syntax of an normal function arrow function do not
have their own this and constructor because they do not have
prototype.
const myFunction=()=>{
console.log(“I am arrow function”);
}

what is first class function?


In Javascript, functions are first class objects. First-class functions
means when functions in that language are treated like any other
variable. a function can be passed as an argument to other
functions, can be returned by another function and can be assigned
as a value to a variable.
For example,

const handler = () => console.log("This is a click handler function");


document.addEventListener("click", handler);

what is first order function?


First-order function is a function that doesn’t accept another
function as an argument and doesn’t return a function as its return
value.

what is higher order function?


Higher-order function is a function that accepts another function
as an argument or returns a function as a return value or both.
example of higher order function :In JavaScript functions, map,
filter and reduce are examples of built-in higher-order functions

what is unary function?


Unary function (i.e. monadic) is a function that accepts exactly one
argument. It stands for a single argument accepted by a function.

Let us take an example of unary function,


const unaryFunction=(a)=>{
console.log(a+10);
}
unaryFunction(34);

what is currying function?


Currying is the process of taking a function with multiple
arguments and turning it into a sequence of functions each with
only a single argument.By applying currying, a n-ary function turns
it into a unary function.Curried functions are great to improve code
reusability and functional composition.

Example of Currying :
const curryUnaryFunction = (a) => (b) => (c) => a + b + c;
curryUnaryFunction(1);
curryUnaryFunction(1)(2);
curryUnaryFunction(1)(2)(3);
let result=curryUnaryFunction(1)(2)(3);
console.log("result",result);

what is pure function?


A Pure function is a function where the return value is depends on
the number of argument accepted by function 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.

what is the difference between let var and const?


1) Var
The scope of a var variable is functional scope.
It can be updated and re-declared into the scope.

2) let
The scope of a let variable is block scope.
It can be updated but cannot be re-declared into the scope.

3) const
The scope of a const variable is block scope.
It cannot be updated or re-declared into the scope.

what do you mean by IIFE function?


IIFE (Immediately Invoked Function Expression) is a JavaScript
function that runs as soon as it is defined.The primary reason to
use an IIFE is to obtain data privacy because any variables declared
within the IIFE cannot be accessed by the outside world. i.e, If you
try to access variables with IIFE then it throws an error.

Example of IIFE function


(function(){
let myvar=6;
console.log("-----",myvar);
})();

what are latest ES6 features?


1) arrow function
2) promise async await
3) let const
4) Hoisting
5) Template Literals
6) multiline string
7) default parameters
8) spread operator
9) Rest operator

what is memoization?
Memoization is a programming technique which attempts to
increase a function’s performance by caching its previously
computed results. Each time a memoized function is called, its
parameters are used to index the cache. If the data is present, then
it can be returned, without executing the entire function. Otherwise
the function is executed and then the result is added to the cache.

what is Hoisting?
Hoisting is a JavaScript mechanism where variables, function
declarations and classes are moved to the top of their scope before
code execution. Remember that JavaScript only hoists declarations,
not initialisation. Let's take a simple example of variable
hoisting,This hoisting makes functions to be safely used in code
before they are declared.

Example of hoisting
message = "The variable Has been hoisted";
console.log(message);
var message;

what are closures?


A function with its lexical scope is called closure.i.e inner function
has access to the outer function variable. In JavaScript, every time a
closure is created with the creation of a function.

The closure has three scope chains listed as follows:


Access to its own scope.
Access to the variables of the outer function.
Access to the global variables.
Example:

function ExampleOfClosure(){
let a=90;
return function add(){
let b=34;
return a+b;
}
}
let result=ExampleOfClosure();
console.log("---result",result());

what do you mean by web storage,local and session storage?


Web storage is an API that provides a mechanism by which
browsers can store key/value pairs locally within the user's
browser, The web storage provides two mechanisms for storing
data on the client.

Local storage:LocalStorage is a type of web storage which is used to


strore information in key value pair.It stores data for current origin
with no expiration date.
Session storage:Session storage is a type of web storage which is
used to strore information in key value pair. It stores data for one
session and the data is lost when the browser tab is closed.

1) Save Data to Local Storage. localStorage.setItem(key, value);


2) Read Data from Local Storage. let lastname =
localStorage.getItem(key);
3) Remove Data from Local Storage. localStorage.removeItem(key);
4) Remove All (Clear Local Storage) localStorage.clear();

what is the difference between DOM and BOM?


1) DOM : DOM stands for Document Object Model it is the structural
representation of all nodes in an HTML document DOM represents
the Ul of your applications. DOM manipulation is required to
dynamically change the content of a web page.

Find an element by
document.getElementById(id)
element id
document.getElementsByTag Find elements by tag
Name(name) name
document.getElementsByClass Find elements by
Name(name) class name

2) BOM : BOM stands for browser object model It is used to interact


with the browser.The default object of browser is window with the
help of window object we can use lots of other properties also like
document ,history,screen ,navigator,location
window.innerHeight();
window.innerWidth();

what is promises ,promise.all and promise.race?


1) Promises : Promises are used to handle asynchronous operations
in JavaScript. They are easy to manage when dealing with multiple
asynchronous operations where callbacks can create callback hell
leading to unmanageable code.promises are the ideal choice for
handling multiple callbacks at the same time, thus avoiding the
undesired callback hell situation. Promises do provide a better
chance to a user to read the code in a more effective and efficient
manner especially it that particular code is used for implementing
multiple asynchronous operations.
let Promise = new Promise((resolve, reject)=>{  
   let a = 3;  
    if(a==3){  
      resolve('Success');  
   }  
   else{  
       reject('Failed');  
  }  
})  
Promise.then((message)=>{  
    console.log("It is then block. The message is: ?+ message)  
}).catch((message)=>{  
console.log("It is Catch block. The message is: ?+ message)  
})  

Benefits of Promises
Improves Code Readability
Better handling of asynchronous operations
Better flow of control definition in asynchronous logic
Better Error Handling

A Promise has four states:


fulfilled: Action related to the promise succeeded
rejected: Action related to the promise failed
pending: Promise is still pending i.e. not fulfilled or rejected yet
settled: Promise has fulfilled or rejected

2) promise.all: Promise.all is a promise that takes an array of


promises as an input, and it gets resolved when all the promises get
resolved or any one of them gets rejected.
For example :
p1 = Promise.resolve(50);
p2 = 200
p3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'geek');
});
Promise.all([p1, p2, p3]).then(function(values) {
console.log(values);
});
Promise.race([promise1 , promise2 , promise3 ]).
then(function(values){
console.log("----------values",values);
})
let result1 = Promise.any([promise1 , promise2 , promise3]);
result1.then((data) => console.log("Any's data: " + data));

3) promise.race : Promise.race() method will return the promise


instance which is firstly resolved or rejected.

what are the advantages of promise over Callback?


Promises are used to handle asynchronous operations in JavaScript.
They are easy to manage when dealing with multiple asynchronous
operations because in promise we get status of each asynchronous
operations where callbacks can create callback hell leading to
unmanageable code.

what is the diffrenece between promise and async await?


promise :
1) Promise is an object representing intermediate state of operation
which is guaranteed to complete its execution at some point in
future.
2) Promise has 3 states – resolved, rejected and pending.
3) Error handling is done using .then() and .catch() methods.

Async/Await
1) Async/Await is a syntactic sugar for promises, a wrapper making
the code execute more synchronously.
2) It does not have any states. It returns a promise either resolved
or rejected.
3) Error handling is done using .try() and .catch() methods.

what do you mean by 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,

what is promise chaining?


The process of executing a sequence of asynchronous tasks one
after another using promises is known as Promise
chaining.Promise Chaining is a simple concept by which we may
initialize another promise inside our .then() method and
accordingly we may execute our results. The function inside then
captures the value returned by the previous promise
new Promise(function(resolve,reject){

setTimeout(()=>resolve(1),1000)

}).then(function(result){

console.log("---first promise",result);
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve(result*2),1000)
})

}).then(function(result){

console.log("---second promise",result);
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve(result*2),1000)
})

}).then(function(result){

console.log("---third promise",result);
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve(result*2),1000)
})

}).then(function(result){
console.log("---fourth promise",result);
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve(result*2),1000)
})
})

what do you mean by event flow,event bublling and event


capturing?
Event flow : Event flow is the order in which event is received on
the web page. When you click an element that is nested in various
other elements, before your click actually reaches its destination, or
target element, it must trigger the click event for each of its parent
elements first, starting at the top with the global window object.
There are two ways of event flow
1) Top to Bottom(Event Capturing)
2) Bottom to Top (Event Bubbling)

Event bubbling : 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 : 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.
what are events?
Events are actions or occurrences that happen in the system you
are programming, which the system tells you about so your code
can react to them. For example, if the user clicks a button on a
webpage, you might want to react to that action by displaying an
information box.

what is the use of stopParopagation method?


The stopPropagation() method prevents propagation of the same
event from being called. Propagation means bubbling up to parent
elements or capturing down to child elements.stopPropagation
method s called on events.

Example of stopPropagation
function func1(event) {
alert("DIV 1");
event.stopPropagation();
}

what is the use of preventDefault method?


The preventDefault() method cancels the event if it is cancelable,
meaning that the default action or behaviour that belongs to the
event will not occur. For example, prevent form submission when
clicking on submit button and prevent opening the page URL when
clicking on hyperlink are some common use cases.

For example, this can be useful when:


Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL
what is the difference between setTimeout and setTimeInterval?
The setTimeout() method is used to call a function or evaluate an
expression after a specified number of milliseconds. For example,
let's log a message after 2 seconds using setTimeout method,

Example of setTimeout()
setTimeout(function () {
console.log("Good morning");
}, 2000);

The setInterval() method is used to call a function or evaluate an


expression at specified intervals (in milliseconds). For example, let's
log a message after 2 seconds using setInterval method,

Example of setInterval()
setInterval(function () {
console.log("Good morning");
}, 2000);

what is the difference between clearTimeOut and ClearInterval?


The clearTimeout() function is used in javascript to clear the
timeout which has been set by setTimeout()function before that. i.e,
The return value of setTimeout() function is stored in a variable and
it’s passed into the clearTimeout() function to clear the timer.

The clearInterval() function is used in javascript to clear the


interval which has been set by setInterval() function. i.e, The return
value returned by setInterval() function is stored in a variable and
it’s passed into the clearInterval() function to clear the interval.

what is the difference between synchronous and asynchronous?


Synchronous : As the name suggests synchronous means to be in a
sequence, i.e. every statement of the code gets executed one by one.
So, basically a statement has to wait for the earlier statement to get
executed.

asynchronous code execution allows to execution of the upcoming


instructions immediately i.e. every statement of the code gets
executed on the basis of upcoming request. So, basically a statement
has no wait for the earlier statement to get executed.

what is the purpose of freeze method?


The Object.freeze() method is used to freeze an object. Freezing an
object does not allow new properties to be added to the object and
prevents removing or altering the existing properties.
Object.freeze() preserves the enumerability, configurability,
writability, and prototype of the object. It returns the passed object
and does not create a frozen copy.

what is spread operator?


The spread operator allows us to copy all elements from the
existing array or object into another array or object.The spread
operator makes deep copies of data if the data is not nested. When
you have nested data in an array or object the spread operator will
create a deep copy of the top most data and a shallow copy of the
nested data.
Example of spread operator
const cars1 = ["AUDI","BMW","TATA","MERCEDES"];
const cars2 = [...cars1];
consoale.log(cars2);

what do you mean by Rest operator?


The rest parameter syntax allows us to represent an indefinite
number of arguments as an array. With the help of a rest
parameter, a function can be called with any number of arguments,
no matter how it was defined

Example of Rest operator

function fun(...input){
let sum = 0;
for(let i=0;i<=input.length;i++){
sum=sum+i;
}
return sum;
}
console.log(fun(1,2,3,4,5)); //15

What are the differences between freeze and seal methods?


If an object is frozen using the Object.freeze() method then its
properties become immutable and no changes can be made in them
whereas if an object is sealed using the Object.seal() method then
the changes can be made in the existing properties of the object.
What is typescript?
TypeScript is a typed superset of JavaScript created by Microsoft
that adds optional types, classes, async/await, and many other
features, and compiles to plain JavaScript. Angular built entirely in
TypeScript and used as a primary language. You can install it
globally as

npm install -g typescript

What are the advantages of typescript over javascript?

Typescript
Typescript is Object oriented programming language
Supports static typing and inheritance
Functions support optional parameters

Javascript
Javascript is scripting language
Supports synamic typing and not support inheritance
No support of optional parameters for functions

REACTJS INTERVIEW QUESTIONS?

what is react?
React is an open-source front-end JavaScript library that is used for
building user interfaces, especially for single-page applications. It is
used for handling view layer for web and mobile apps.
React follows components base approach which allows to make
reusable UI component.

what are the major feature of react?


Uses JSX syntax, a syntax extension of JS that allows developers to
write HTML in their JS code.
It uses VirtualDOM instead of RealDOM considering that RealDOM
manipulations are expensive.
Supports server-side rendering.
Follows Unidirectional data flow or data binding.
Uses reusable/composable UI components to develop the view.

What is JSX?
JSX stands for JavaScript XML. It is simply a syntax extension of
JavaScript. It allows us to directly write HTML in React (within
JavaScript code).

Syntax:
const element = <h1>Welcome to GeeksforGeeks.</h1>;

Characteristics of JSX:
1) JSX is not mandatory to use there are other ways to achieve the
same thing but using JSX makes it easier to develop react
application.
2) JSX allows writing expression in { }. The expression can be any JS
expression or React variable.
To insert a large block of HTML we have to write it in a parenthesis
i.e, ().
3) JSX produces react elements.
JSX follows XML rule.
4) After compilation, JSX expressions become regular JavaScript
function calls.
5) JSX uses camelcase notation for naming HTML attributes. For
example, tabindex in HTML is used as tabIndex in JSX.

Advantages of JSX:

JSX makes it easier to write or add HTML in React.


JSX can easily convert HTML tags to react elements.
It is faster than regular JavaScript.
JSX allows us to put HTML elements in DOM without using
appendChild() or createElement() method.
As JSX is an expression, we can use it inside of if statements and for
loops, assign it to variables, accept it as arguments, or return it
from functions.
JSX prevents XSS (cross-site-scripting) attacks popularly known as
injection attacks.

What is the difference between Element and Component?


React Element: It is the basic building block in a react application,
it is an object representation of a virtual DOM node. React Element
contains both type and property. React Element does not have any
methods,React elemet is showing on web page with the help of
ReactDOM.render(ele,document.getElementById(“root”))

import React from 'react';


import ReactDOM from 'react-dom';
  
const ele1 =<h1>Welcome</h1>;
  
// Simple javaScript to get the div with id ="root"
ReactDOM.render(ele1,document.getElementById("root")); 
React Component: It is independent and reusable. It returns the
virtual DOM of the element. One may or may not pass any
parameter while creating a component. A component can be further
described into functional components and class components.

import React from 'react'


const myworkExample = () => {
return (
<div>myworkExample</div>
)
}
export default myworkExample

Note: Always start the components name with the capital letter,
react consider the lowercase component name as HTML tags so it
will not show the component.

What is the difference between class component and functional


component?
1) Functional Components
a) A functional component is just a plain JavaScript pure function
that accepts props as an argument and returns a React
element(JSX).
b) There is no render method used in functional components.
c) Functional component run from top to bottom and once the
function is returned it cant be kept alive.
d) Also known as Stateless components as they simply accept data
and display them in some form, that they are mainly responsible
for rendering UI.
e) React lifecycle methods (for example, componentDidMount)
cannot be used in functional components.
f) Hooks can be easily used in functional components to make them
Stateful.
example: const [name,SetName]= React.useState(‘ ‘);

import React from 'react'


const myworkExample = () => {
return (
<div>myworkExample</div>
)
}
export default myworkExample

2) class component
a) A class component requires you to extend from React.
Component and create a render function which returns a React
element.
b) It must have the render() method returning JSX (which is
syntactically similar to HTML)
c) Class component is instantiated and different life cycle method is
kept alive and being run and invoked depending on phase of class
component.
d) Also known as Stateful components because they implement
logic and state.
e) React lifecycle methods can be used inside class components (for
example, componentDidMount).
class Car extends React.Component {
render() {

return <h2>Hi, I am a Car!</h2>;

What is the difference between stateless and stateful component?


State Full
1. Stateful component plays with all life cycle methods of React.
2. This component will modify the state.
3. We can access all the method inside state full component
4< stateful component is also known as class component

State Less
1. The stateless component only receives props from the parent
component and returns you JSX elements.
2. The stateless component doesn’t play with any lifecycle methods
of React and doesn’t play with the component state.
3. stateless component is also known as functional component

What are Pure Components?


If we extend a class with Pure Component, there is no need for
shouldComponentUpdate() Lifecycle Method. ReactJS Pure
Component Class compares current state and props with new props
and states to decide whether the React component should re-render
itself or Not.
If the previous value of state or props and the new value of state or
props is the same, the component will not re-render itself. Since
Pure Components restricts the re-rendering when there is no use of
re-rendering of the component. Pure Components are Class
Components which extends React.PureComponent.

what are the difference between state and props?


1) props
Props are read-only && immutable
Props allow you to pass data from one component to other
components as an argument. And it can access by only child
component.

2) state
State is mutable. And they holds information about the
components.State cannot be accessed by child components.
It can be used for rendering dynamic changes with the component.

What are synthetic events in React?


The react event handling system is known as Synthetic
Events.Handling events with react have some syntactic differences
from handling events on DOM. These are: React events are named
as camelCase instead of lowercase.SyntheticEvent including
stopPropagation() and preventDefault(), except the events work
identically across all browsers.

How to create refs and what is the use of it?


Refs are used in cases where we want to change the value of a child
component, without making use of props and all. They also provide
us with good functionality as we can use callbacks with them.
Example of refs : later

What is Virtual DOM?and How it works?


The Virtual DOM (VDOM) is an in-memory representation of Real
DOM. The representation of a UI is kept in memory and synced with
the "real" DOM. It's a step that happens between the render
function being called and the displaying of elements on the screen.
This entire process is called reconciliation.

The Virtual DOM works in three simple steps.

Whenever any underlying data changes, the entire UI is re-


rendered in Virtual DOM representation.
Then the difference between the previous DOM representation and
the new one is calculated.
Once the calculations are done, the real DOM will be updated with
only the things that have actually changed.

Difference between real dom and virtual dom?


1) Real DOM
DOM manipulation is very expensive
There is too much memory wastage
It updates Slow
It can directly update HTML
Creates a new DOM if the element updates.
It allows us to directly target any specific
node (HTML element)
It represents the Ul of your application
2) Virtual DOM
DOM manipulation is very easy
No memory wastage
It updates fast
It can’t update HTML directly
Update the JSX if the element update
It is only a virtual representation of the DOM

what is the difference between deep copy and shallow copy?


1) Shallow Copy
Shallow Copy stores the references of objects to the original
memory address.
Shallow Copy reflects changes made to the new/copied object in the
original object.
Shallow Copy stores the copy of the original object and points the
references to the objects.
Shallow copy is faster

2) Deep copy
Deep copy stores copies of the object’s value.
Deep copy doesn’t reflect changes made to the new/copied object in
the original object.
Deep copy stores the copy of the original object and recursively
copies the objects as well.
Deep copy is comparatively slower.

what are the controlled and uncontrolled component?


Controlled Components: In React, Controlled Components are
those in which form’s data is handled by the component’s state. It
takes its current value through props and makes changes through
callbacks like onClick, onChange, etc. A parent component manages
its own state and passes the new values as props to the controlled
component.

Uncontrolled Components: Uncontrolled Components are the


components that are not controlled by the React state and are
handled by the DOM (Document Object Model). So in order to access
any value that has been entered we take the help of refs.

What are the lifecycle methods and different phase of React


Lifecycle?
 A React Component can go through four stages of its life as follows. 
 
•Initialization: This is the stage where the component is
constructed with the given Props and default state. This is done in
the constructor of a Component Class.
•Mounting: Mounting is the stage of rendering the JSX returned by

the render method itself.


•Updating: Updating is the stage when the state of a component is

updated and the application is repainted.


•Unmounting: As the name suggests Unmounting is the final step of

the component lifecycle where the component is removed from the


page.

Component Lifecycle method

Initialization: In this phase, the developer has to define the props


and initial state of the component this is generally done in the
constructor of the component

componentWillMount() : this function is invoked right before the


component is mounted on the DOM i.e. this function gets invoked
once before the render() function is executed for the first time.

componentDidMount() : this function is invoked right after the


component is mounted on the DOM i.e. this function gets invoked
once after the render() function is executed for the first time

componentWillReceiveProps() : This function is invoked before a


mounted component gets its props reassigned. The function is
passed the new set of Props which may or may not be identical to
the original Props.

setState() : This function is used to update the state of a component.

shouldComponentUpdate() : shouldComponentUpdate() is invoked


before rendering an already mounted component when new props
or state are being received.

•componentWillUpdate() :this function is invoked before the


component is rerendered i.e. this function gets invoked once before
the render() function is executed after the updation of State or
Props.

•componentDidUpdate() : Similarly this function is invoked after


the component is rerendered i.e. this function gets invoked once
after the render() function is executed after the updation of State or
Props.

componentWillUnmount() : This function is invoked before the


component is finally unmounted from the DOM i.e. this function
gets invoked once before the component is removed from the page
and this denotes the end of the lifecycle.

What are Higher-Order components?


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 behavior 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.

App.js

import React, { Component } from 'react';


import Hoc from './HOC';
class App extends Component {
render() {
return ( <div> Higher-Order Component Tutorial </div> )
}
}
App = Hoc(App);
export default App;

// HOC.js

import React, {Component} from 'react' ;

export default function Hoc(HocComponent) {

return class extends Component {

render() {

return (

<div>

<HocComponent></HocComponent>
</div>

);

What is reconciliation?
The mechanism to diff one tree with another to determine which
parts need to be changed and then update the original DOM with it
is called Reconciliation

What are fragments? and Why fragments are better than


container divs?
React Fragments is faster and more space-efficient as compared to
an extra div (no need to create an extra DOM node). This may not
significantly impact a small application but benefits very large
applications with very deep or large trees

Therefore, React fragments are better than the ‘div’ tags. With
React Fragment, you can render multiple elements of a component
without adding extra div tags. We can write cleaner, more readable
code with React Fragments. It takes up less memory and renders
components faster. Each component is rendered as expected.

How to apply validation on props in React?


Need of Validating Props in React JS: Props are used to passing the
read-only attributes to React components. For the proper
functioning of components and to avoid future bugs and glitches it
is necessary that props are passed correctly. Hence, it is required to
use props validation for improving react component’s performance.

React JS has an inbuilt feature for validating props data type to


make sure that values passed through props are valid. React
components have a property called propTypes which is used to
setup data type validation.

Syntax: The syntax to use propTypes is shown below.


class Component extends React.Component {
render() {}
}

Component.propTypes = {/* definition goes here*/};


Validators: The propTypes object contains a list of validators for
basic data types, some of them are:

PropTypes.any : This means the prop can be of any data type.


PropTypes.bool: This means the prop should be a boolean.
PropTypes.number: This means the prop should be a number.
PropTypes.string: This means the prop should be a string.

What are the advantages of React?What are the limitations of


React?
Advantages
1. Easy to Learn and USe
2. Creating Dynamic Web Applications Becomes Easier
3. Reusable Components
4. Performance Enhancement
5. The Support of Handy Tools
6. Known to be SEO Friendly
7. The Benefit of Having JavaScript Library
8. Scope for Testing the Codes

Disadvantages
1. The high pace of development
2. Poor Documentation
3. View Part
4. JSX as a barrier

What is the purpose of render() method?


We can use the ReactDOM.render() in the application using the
declaration of HTML code and the HTML element. The goal of this
function is to represent the imposed HTML code within the
specified HTML element tags. It helps to redirect the HTML page
with the help of the render() function.

How do you memoize a component?


To implement memoization in a class component, we’ll
use React.PureComponent. React.PureComponent implements shou
ldComponentUpdate(), which does a shallow comparison on state
and props and renders the React component only if there’s a change
in the props or state.

To implement memoization in functional React components, we’ll


use React.memo().React.memo() is a higher order component (HOC)
that does a similar job to PureComponent, avoiding unnecessary
re-renders.
What is React Router?
React Router is a powerful routing library built on top of React that
helps you add new screens and flows to your application incredibly
quickly, all while keeping the URL in sync with what's being
displayed on the page.

explain react architecture?


React app starts with a single root component.

Root component is build using one or more component.

Each component can be nested with other component to any level.

Composition is one of the core concepts of React library. So, each


component is build by composing smaller components instead of
inheriting one component from another component.

Most of the components are user interface components.

React app can include third party component for specific purpose
such as routing, animation, state management, etc.

What is Redux?
Redux is an open-source JavaScript library used to manage
application state. React uses Redux for building the user interface.
It was first introduced by Dan Abramov and Andrew Clark in 2015.

React Redux is the official React binding for Redux. It allows React
components to read data from a Redux Store, and dispatch Actions
to the Store to update data. Redux helps apps to scale by providing a
sensible way to manage state through a unidirectional data flow
model. React Redux is conceptually simple. It subscribes to the
Redux store, checks to see if the data which your component wants
have changed, and re-renders your component.
Redux was inspired by Flux. Redux studied the Flux architecture
and omitted unnecessary complexity.

Redux does not have Dispatcher concept.


Redux has an only Store whereas Flux has many Stores.
The Action objects will be received and handled directly by Store.

explain the working flow of redux?


There are four fundamental concepts that govern the flow of data
in React-Redux applications.

Redux store: The Redux store, simply put, is an object that holds
the application state. A redux store can consist of small state
objects which are combined into one large object. Any component in
the application can easily access this state (store) by hooking up to
it through the connect method.

Action creators: Action creators, as the name suggests, are


functions that return actions (objects). Action creators are invoked
when the user interacts with the application through its UI (button
click, form submission, etc) or at certain points in a component’s
lifecycle (component mounts, component un-mounts, etc).

Actions: Actions are simple objects which conventionally have two


properties- type and payload. The type property is usually a string
that specifies identifies the action, and the payload is an optional
property that contains some data that is required to perform any
particular task. The main function of action is to send data from the
application to the Redux store.
Reducers: Reducers are pure functions that update the state of the
application in response to actions. Reducers take a previous state
and an action as the input and return a modified version of the
state. Since the state is immutable, a reducer always returns a new
state, which is an updated version of the previous state.

React-Redux Application Flow

1) The flow of data in a React-Redux application begins at the


component level when the user interacts with the application UI.

2) This interaction leads to the action creators dispatching an


action.When an action is dispatched, it is received by the root
reducer of the application and is passed on to all the reducers.

3) Thus, it becomes the reducer’s task to determine if it needs to


update the state based on the dispatched action.

4) Each reducer in the application accepts the dispatched action


and if the type of the dispatched action matches, it returns a newly
updated state.

what are hooks?


Hooks are JavaScript functions that manage the state's behaviour
and side effects by isolating them from a component. So, we can
now isolate all the stateful logic in hooks and use (compose them, as
hooks are functions, too) into the components.
You need to follow two rules in order to use hooks,

Call Hooks only at the top level of your react functions. i.e, You
shouldn’t call Hooks inside loops, conditions, or nested functions.
This will ensure that Hooks are called in the same order each time a
component renders and it preserves the state of Hooks between
multiple useState and useEffect calls.
Call Hooks from React Functions only. i.e, You shouldn’t call Hooks
from regular JavaScript functions.

mostly used hooks are :


1) useState()
2) useEffect()
3) useContext()
4) useReducer()
5) usecallback()
6) useMemo()

how to achieve component life cycle in functional components?


we can achieve component lifecycle in functional component using
hooks useEffect

1) useEffect()=>{

,[]} => intial state

2) useEffect()=>{
,[name]} => updating state

3) 2) useEffect()=>{
return ()
,[name]} => unMounting state

explain following hooks


useeffect(),useState(),useRef(),useMemo(),useContext(),useReducer
()?

1) useEffect() =
The useEffect Hook allows you to perform side effects in your
components.
Some examples of side effects are: fetching data, directly updating
the DOM, and timers.
useEffect accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)
2) useState()=
The React useState Hook allows us to track state in a function
component.
State generally refers to data or properties that need to be tracking
in an application.
with the help of useStatye we can implement dynamic nature of
componene and also provide initial state.

3) useRef()=
The useRef Hook allows you to persist values between renders. It
can be used to store a mutable value that does not cause a re-render
when updated. It can be used to access a DOM element directly.
import React, {Fragment, useRef} from 'react';

function App() {

// Creating a ref object using useRef hook


const focusPoint = useRef(null);
const onClickHandler = () => {
focusPoint.current.value =
"The quick brown fox jumps over the lazy dog";
focusPoint.current.focus();
};
return (
<Fragment>
<div>
<button onClick={onClickHandler}>
ACTION
</button>
</div>
<label>
Click on the action button to
focus and populate the text.
</label><br/>
<textarea ref={focusPoint} />
</Fragment>
);
};

export default App;


4) useMemo()=return memoization value

5)useContext()=
React Context is a way to manage state globally.
It can be used together with the useState Hook to share state
between deeply nested components more easily than with useState
alone.

6)useReducer()=
The useReducer hook is similar to useState, but gives us a more
structured approach for updating complex values.
We typically use useReducer when our state has multiple sub-
values, e.g. an object containing keys that we want to update
independently.

The useReducer hook requires 2 arguments, and has an optional 3rd


argument:
reducer - a pure function that takes a state and an action, and
returns a new state value based on the action
initialState - any initial state value, just like useState
initializer (optional) - this is uncommon, but we'll briefly introduce
it later.
The useReducer hook returns the current state, and a dispatch
function to update the state.

7) useCallback()=return memoization function

what do you mean by propdrilling()?


Anyone who has worked in React would have faced this and if not
then will face it definitely. Prop drilling is basically a situation
when the same data is being sent at almost every level due to
requirements in the final level. Here is a diagram to demonstrate it
better. Data needed to be sent from Parent to ChildC. In this article
different ways to do that are discussed.

how to pass data from child component to parent component()?


Following are the steps to pass data from child component to
parent component:

1) In the parent component, create a callback function. This callback


function will retrieve the data from the child component.

2) Pass the callback function to the child as a props from the parent
component.

3) The child component calls the parent callback function using


props and passes the data to the parent component.

CSS INTERVIEW QUESTIONS

difference between display none and visibility hidden?


visibility:hidden hides the element, but it still takes up space in the
layout. display:none removes the element from the document. It
does not take up any space.

difference between display grid and flexbox?


Grid utilizes a two-dimensional system that allows placing items in
rows and columns, making it easier to create complex layouts. On
the other hand, Flexbox is a one-dimensional system that works
with elements placed in a linear order.

what are the new features introduced in CSS3?


And while CSS allows web designers to use animations, CSS3 ups the
stakes with more complex animation properties such as
transforms, transitions, and special effects. Opacity. This property
lets web designers make web page elements partially or fully
transparent.

what are the difference kind of position(fixed,relative ....)?


The CSS position property is used to set position for an element. it
is also used to place an element behind another 
Absolute: absolute position is actually set relative to the element's
parent. if no parent is available then the relative place to the page
itself.

Relative: "Relative to itself". Setting position: relative; on an


element and no other positioning attributes, it will no effect on its
positioning. It allows the use of z-index on the element Any child
element will be absolutely positioned within that block.

Fixed: The element is positioned relative to the viewport or the


browser window itself. viewport doesn't change if you scroll and
hence the fixed element will stay right in the same position.

Static: This is a by default position for HTML elements. It always


positions an element according to the normal flow of the page. It is
not affected by the top, bottom, left and right properties.

Sticky: Sticky positioning is a hybrid of relative and fixed


positioning. The element is treated as relative positioned until it
crosses a specified threshold, at which point it is treated as fixed
positioned.

what are the difference kind of display(fixed,relative ....)?


1) grid
Displays an element as a block-level grid container

2) inline-block
Displays an element as an inline-level block container. The element
itself is formatted as an inline element, but you can apply height
and width values
3) inline-flex
Displays an element as an inline-level flex container

what do you mean by grid?


CSS Grid Layout is a two-dimensional layout system for the web. It
lets you lay content out in rows and columns. It has many features
that make building complex layouts straightforward

What is the Box model in CSS? Which CSS properties are a part of
it?
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.

What are the different types of Selectors in CSS?


A CSS selector selects the HTML element(s) for styling purpose. CSS
selectors select HTML elements according to its id, class, type,
attribute etc.

There are many basic different types of selectors.

Element Selector :The element selector selects HTML elements


based on the element name (or tag) for example p, h1, div, span, etc.
Id Selector : The id selector uses the id attribute of an HTML
element to select a specific element. An id of element is unique on a
page to use id selector.
Class Selector :The class selector selects HTML elements with a
specific class attribute.
Universal Selector : The Universal selector (*) in CSS is used to
select all the elements in a HTML document. It also includes other
elements which are inside under another element.
Group Selector :This selector is used to style all comma separated
elements with the same style.
Attribute Selector :The attribute selector [attribute] is used to
select the elements with a specified attribute or attribute value.
Pseudo-Class Selector : It is used to style a special type of state of
any element. For example- It is used to style an element when a
mouse cursor hovers over it.
Note: We use a single colon(:) in the case of Pseudo-Class Selector.
h1:hover{
background-color: aqua;
}

Pseudo-Element Selector : It is used to style any specific part of the


element. For Example- It is used to style the first letter or the first
line of any element.
Note: We use a double colon(::) in the case of Pseudo-Element
Selector.
p::first-line{
background-color: goldenrod;
}

Difference between reset vs normalize CSS?. How do they differ?


Reset CSS: CSS resets aim to remove all built-in browser styling.
For example margins, paddings, font-sizes of all elements are reset
to be the same.
Normalize CSS: Normalize CSS aims to make built-in browser
styling consistent across browsers. It also corrects bugs for
common browser dependencies.

What is the difference between inline, inline-block, and block?


Block Element: The block elements always start on a new line. They
will also take space for an entire row or width. List of block
elements are <div>, <p>.

Inline Elements: Inline elements don't start on a new line, they


appear on the same line as the content and tags beside them. Some
examples of inline elements are <a>, <span> , <strong>, and <img>
tags.

Inline Block Elements: Inline-block elements are similar to inline


elements, except they can have padding and margins and set height
and width values.

What are Pseudo elements and Pseudo classes?


Pseudo-elements allows us to create items that do not normally
exist in the document tree, for example ::after.

::before
::after
::first-letter
::first-line
::selection
In the below example, the color will appear only on the first line of
the paragraph.
p: :first-line {
color: #ffOOOO;
font-variant: small-caps;
}
Pseudo-classes select regular elements but under certain
conditions like when the user is hovering over the link.

:link
:visited
:hover
:active
:focus
Example of the pseudo-class, In the below example, the color
applies to the anchor tag when it’s hovered.

/* mouse over link */


a:hover {
color: #FFOOFF;
}

Does margin-top or margin-bottom have an effect on inline


elements?
No, it doesn’t affect the inline elements. Inline elements flow with
the contents of the page.

What are the differences between adaptive design and responsive


design?
Adaptive design :
Adaptive design focuses on developing websites based on multiple
fixed layout sizes.
It takes a lot of time and effort to first examine the options and
realities of the end users and then design best possible adaptive
solutions them.
Gives a lot of control over the design to develop sites for specific
screens.

responsive design
Responsive design focuses on showing content on the basis of
available browser space.
Generally, Responsive design takes much less work to build and
design fluid websites that can accomodate content from screen
depending on the screen size.
No much control over the design is offered here.

How is border-box different from content-box?


border-box and content-box are the two different values of box-
sizing.

content-box: This is the default value of box-sizing. The dimension


of element only includes ‘height’ and ‘width’ and does not include
‘border’ and ‘padding’ given to element. Padding and Border take
space outside the element.

border-box: In this value, not only width and height properties are
included but you will find padding and border inside of the box for
example .box {width: 200px; border: 10px solid black;} renders a box
that is 200px wide.

What are the properties of flexbox?


The properties of flexbox are as follows:
flex-direction: This property helps in defining the direction the
container should stack the items targetted for flex. The values of
this property can be

row: Stacks items horizontally from left to right in the flex


container.
column: Stacks items vertically from top to bottom in the flex
container.
row-reverse: Stacks items horizontally from right to left in the flex
container.
column-reverse: Stacks items vertically from bottom to top in the
flex container.

flex-wrap: This property specifies of the flex items should be


wrapped or not. Possible values are:

wrap: The flex items would be wrapped if needed.

nowrap: This is the default value that says the items won’t be
wrapped.

wrap-reverse: This specifies that the items will be wrapped if


needed but in reverse order.

flex-flow: This property is used for setting both flex-direction and


flex-wrap properties in one statement.

justify-content: Used for aligning the flex items. Possible values


are:

center: It means that all the flex items are present at the center of
the container.

flex-start: This value states that the items are aligned at the start of
the container. This is the default value.

flex-end: This value ensures the items are aligned at the end of the
container.

space-around: This value displays the items having space between,


before, around the items.

space-between: This value displays items with spaces between the


lines.

align-items: This is used for aligning flex items.

align-content: This is used for aligning the flex lines.

Can you name the four types of @media properties?

The four types of @media properties are:


All → It’s the default property. Used for all media-type devices.
Screen → Used for computer screen, mobile screen.
Print → Used for printers.
Speech → Used for screen readers.

What are the different ways to hide the element using CSS?
There are the following CSS properties use to hide an element.

Absolute position
Color
Clip-path
Display
filter
Measurements
Opacity
Transform
Visibility

HTML interview questions

difference between attribute and property?

Image result for difference between attribute and property?


Attributes are defined by HTML, but properties are defined by the
DOM. The value of an attribute is constant, but the value of a
property is variable. The attribute's main role is to initializes the
DOM properties. So, once the DOM initialization complete, the
attributes job is done.

what are new tags introduced in HTML5?


article.
aside.
audio.
datalist.
details.
embed.
video

what are the advantages of usidng Header and footer tag?

A header is the top margin of each page, and a footer is the bottom
margin of each page. Headers and footers are useful for including
material that you want to appear on every page of a document such
as your name, the title of the document, or page numbers.

what are inline elements?


Inline elements just take up the space that is absolutely necessary
for the content and does not start from a new line.
Example:- <span>, <a>, <strong>, <img>, <button>, <em>, <select>,
<abbr>, <label>, <sub>, <cite>, <abbr>, <script>, <label>, <i>, <input>,
<output>, <q>, etc.

What is semantic HTML?


Semantic elements are those which describe the particular meaning
to the browser and the developer. Elements like <form>, <table>,
<article>, <figure>, etc., are semantic elements.

What are empty elements?


An empty element is a component that doesn't have any embedded
elements or text elements. Empty elements do not have successor
nodes. In other words, the tags that do not contain any closing tags
are empty tags. Empty tags contain only the opening tag but they
perform some action in the webpage.

What are void elements in HTML?


HTML elements which do not have closing tags or do not need to be
closed are Void elements. For Example <br />, <img />, <hr />, etc.

What is the ‘class’ attribute in HTML?


The class attribute is used to specify the class name for an HTML
element. Multiple elements in HTML can have the same class value.
Also, it is mainly used to associate the styles written in the
stylesheet with the HTML elements.

What is the difference between the ‘id’ attribute and the ‘class’
attribute of HTML elements?
Multiple elements in HTML can have the same class value, whereas
a value of id attribute of one element cannot be associated with
another HTML element.

Define multipart form data?


Multipart form data is one of the values of the enctype attribute. It
is used to send the file data to the server-side for processing. The
other valid values of the enctype attribute are text/plain and
application/x-www-form-urlencoded.

How is Cell Padding different from Cell Spacing?


Cell Spacing is the space or gap between two consecutive cells.
Whereas, Cell Padding is the space or gap between the text/ content
of the cell and the edge/ border of the cell. Please refer to the above
figure example to find the difference.

In how many ways can we position an HTML element? Or what are


the permissible values of the position attribute?

There are mainly 7 values of position attribute that can be used to


position an HTML element:

static: Default value. Here the element is positioned according to


the normal flow of the document.
absolute: Here the element is positioned relative to its parent
element. The final position is determined by the values of left,
right, top, bottom.
fixed: This is similar to absolute except here the elements are
positioned relative to the <html> element.
relative: Here the element is positioned according to the normal
flow of the document and positioned relative to its original/ normal
position.
initial: This resets the property to its default value.
inherit: Here the element inherits or takes the property of its
parent.

In how many ways you can display HTML elements?

inline: Using this we can display any block-level element as an


inline element. The height and width attribute values of the
element will not affect.
block: using this, we can display any inline element as a block-level
element.
inline-block: This property is similar to inline, except by using the
display as inline-block, we can actually format the element using
height and width values.
flex: It displays the container and element as a flexible structure. It
follows flexbox property.
inline-flex: It displays the flex container as an inline element while
its content follows the flexbox properties.
grid: It displays the HTML elements as a grid container.
none: Using this property we can hide the HTML element.

How to specify the link in HTML and explain the target attribute?

HTML provides a hyperlink - <a> tag to specify the links in a


webpage. The ‘href’ attribute is used to specify the link and the
‘target’ attribute is used to specify, where do we want to open the
linked document. The ‘target’ attribute can have the following
values:

_self: This is a default value. It opens the document in the same


window or tab as it was clicked.
_blank: It opens the document in a new window or tab.
_parent: It opens the document in a parent frame.
_top: It opens the document in a full-body window

How do you handle API calls in React Application?


Using fetch : fetch API provides a fetch() method defined on the
window object fetch is built into modern browser we don’t need to
install it fetch use the body property it has to be stringyfied thats
why we need to call the .json method on the response.

fetch("https://reqres.in/api/users")
.then(res => res.json())
.then(data => console.log(data))

Using Axios: Axios is third party package which we need to


installed axios provide axios method axios has url in request object
and it has built in XSRF protecyion axios use the data property and
data contains the object we don’t need to explicitly converted the
object into JSON.

 axios
  .get("https://jsonplaceholder.typicode.com/customers")
  .then(response => console.log(response .data))
  .catch(error => console.log(error));
 
How do you chain multiple API Calls that is depending on the
previous request?
Ans : with the help of async await we can handle chaining of
multiple API calls because await suspend the called function
execution until the promise returns a result for that execution.
async and await allows you to wrap your code using a try and catch
to handle errors. &

reqAccountAndTransactions = async () => {


const accountInfo = await fetch(`http://localhost:3000/api/account/$
{accountId}`).then(res => res.json())
const transactions = await fetch(`http://localhost:3000/api/transaction/$
{accountInfo.transactionBatchId}`)
.then(res => res.json())
}

How do avoid mutating an array when performing an operation?

const myArray = [1, 2, 3, 4, 5, 6, 7];


console.log(myArray[2]);
Object.freeze(myArray);
myArray[2] = 17;
console.log(myArray[2]);

How to optimize React application?


1) We can optimize react application using some rules like make
component memoization using useCallBack and
React.PureComponent
2) Using Production Mode Flag in Webpack
3) Use React.Fragments to Avoid Additional HTML Element
Wrappers
4) Avoid Inline Function Definition in the Render Function.
5)Avoid using Index as Key for map
6) Spreading props on DOM elements <div {...props}></div>
7) implement Lazy Loading using React.Lazy

Explain this keyword in with arrow function and normal function


in react?
1) The handling of this is also different in arrow functions
compared to regular functions.
2) with arrow functions there are no binding of this.
3) In regular functions the this keyword represented the object that
called the function, which could be the window, the document, a
button or whatever.
4) With arrow functions the this keyword always represents the
object that defined the arrow function.

What are the common challenges you have facing while working
with react application?
So when I was novie programmer to React i am facing some
challenges while developing react application like to manage big
data list or render data conditionally or stop useless renders ,
implement search engine optimization in react application or
decomposition of the logical and UI layers etc these are the
challenges i am facing while developing react application.

How to send data from child component to parent component?

1. In the parent component, create a callback function. This callback


function will retrieve the data from the child component.

2. Pass the callback function to the child as a props from the parent

component.

3. The child component calls the parent callback function using props

and passes the data to the parent component.

For example :

import child from './child'


export default function Parent(){
function callBack(childData){
return (
<div>
<p>
this is child message{childData}
</p>
</div>
)
}
return (
<div>
<p>parent to child</p>
<child handleCallback={callBack} />
</div>
);
}

export default function Child(props){


var message="Please send this message"
return(
<div>
{props.handleCallback(message)}
</div>
)
}

What are the different way to communicate between component?


1) Passing data from parent to child can be communicate using the props.

2) Passing data from parent to child can be communicate using the


callbacks

3) Instance methods – UseRef:

Just three steps are required to set up the instance methods:

1. Define a method in the child component

2. Add a ref attribute that creates a reference to the child


component  ChildComponent2  in the parent

component  ParentComponent1 .

3. Call the child component method from the parent.

4) Redux is an efficient way of passing props into components irrespective


of their hierarchy. It’s basically a single state tree maintained outside the
component hierarchy but which is designed to connect easily to your
components,
5) React Context API:
Where the Api call is handle in class component and functional
component?
1) Basically we do API calls in componentDidMount() life cycle method in
React class components.
2) You can make API calls by using useEffect and passing in an empty array
or object as the second argument as a replacement
for componentDidMount(). The key here is the second argument. If you
don't provide an empty array or object as the second argument, the API call
will be called on every render.

How to manage if our form have 25 fields over useState?

What is destructuring?
Destructuring assignment is a special syntax that allows us to “unpack”
arrays or objects into a bunch of variables, as sometimes that’s more
convenient.
What is event loop?what are the precedence in event loop in
setTimeout() and promise()
Event loop in JavaScript is a mechanism through which the ‘calls
waiting for execution’ in the callback queue/job queue can be put on
the call stack.For any event from the callback queue/job queue to
come to call stack, the call stack will have to be empty.
https://www.scaler.com/topics/javascript/event-loop-in-
javascript/

How to update a component in every second?

To update a component every second in React, you can use


the setInterval()  method. This method takes two arguments: a callback
function and a time interval in milliseconds.

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

function MyComponent() {
const [time, setTime] = useState(new Date());

useEffect(() => {
const interval = setInterval(() => {
setTime(new Date());
}, 1000);

return () => clearInterval(interval);


}, []);

return <p>The current time is: {time.toLocaleTimeString()}</p>;


}

what is refs? and useRef?


A ref is defined as any value that does not trigger a component re-render
when it is changed. This behavior is contrary to the function of states and
props. A ref can be created in two ways- by the useRef hook or by the
createRef function.

useRef: The useRef is a hook that uses the same ref throughout. It saves its
value between re-renders in a functional component and doesn’t create a
new instance of the ref for every re-render. It persists the existing ref
between re-renders.

createRef: The createRef is a function that creates a new ref every time.


Unlike the useRef, it does not save its value between re-renders, instead
creates a new instance of the ref for every re-render. Thus implying that it
does not persist the existing ref between re-renders.

https://www.geeksforgeeks.org/difference-between-useref-and-
createref-in-reactjs/

Advantages of using functionsl component over class component?


•Easier to test: You don’t have to worry about hidden state and
there aren’t as many side effects when it comes to functional
components, so for every input, the functions will have exactly one
output.

•Easier to read/write: The syntax is less complex than that of class


components, and it’s easier to read due to knowing how much you
can’t do with functional components already. The use of prop
destructuring makes it really beneficial to see what’s going on and
what’s coming out of the component.

•Easier to debug: Again, functional components depend on the


props they are given and don’t reply on state. There isn’t a reason
to console.log() your state to constantly understand the changes
that are going on.

how to pass data in sibling components in react?
Between Siblings :(ii) Using Redux. (iii) Using React's Context API.

https://dev.to/andydziabo/how-to-pass-data-between-sibling-
components-in-react-2cjg

redux is synchronous or asynchronous?


The flow of Redux's state management tasks is completely synchronous:
dispatching an action immediately generates the chain of calls to
middleware and reducers to carry out the state transition

what are the methods we call in redux?


To create a store the createStore(reducer, [initialState],
[enhancer]) function is used to create a new store. It takes three
arguments:

•reducer - A reducing function. We will describe it below.


•initialState - The initial state of the store.

•enhancer - Can be used to enhance the Redux store and add third-

party libraries and middleware for logging, persistant storage, etc.

The Redux store API is tiny and has only four methods:

•store.getState() - Returns the current state object tree.


•store.dispatch(action) - Dispatch an action to change the state.

•store.subscribe(listener) - Listen to changes in the state tree.

•store.replaceReducer(nextReducer) - Replaces the current reducer

with another. This method is used in advanced use cases such


as code splitting.
what are the difference between react redux and react context
API?
React Context
1) useContext is a hook.
2) Changes are made with the Context value.
3) We can change the state in it.
4) It re-renders all components whenever there is any update in the
provider’s value prop.
5) useContext is better to use with small applications.
6) useContext is easy to understand and requires less code.

React-Redux
1) Redux is a state management library.
2) It is used to manage data and state.
3) Changes are made with pure functions i.e. reducers.
4) The state is read-only. We cannot change them directly.
5) It only re-render the updated components.
6) It is perfect for larger applications.
7) Redux quite complex to understand.

what are the rules that must be followed by react hooks?


Hooks can only be called inside React function components.
Hooks can only be called at the top level of a component
Hooks cannot be conditional

difference between margin and padding?


1. Padding represents the amount of inner space an element has,
while the margin is whitespace available surrounding an
element.
2. It’s not possible to set padding to auto padding. However, you
can use automatic settings for margins.
3. It’s not possible to use negative values when defining padding,
but you can with margins.
4. Padding can be impacted by the styling of other elements on a
website. Margin won’t be impacted by the stylization of other
elements on a website.
5.
what is flexbox?jstify content and align item.
justify-content — controls alignment of all items on the main axis.
align-items — controls alignment of all items on the cross axis.
align-self — controls alignment of an individual flex item on the cross axis.

what is lazy loading?


lazy loading is a design pattern. It allows you to load parts of your
application on-demand to reduce the initial load time. For example,
you can initially load the components and modules related to user
login and registration. Then, you can load the rest of the
components based on user navigation.

why api call in react always use inside useEffect?

the useEffect hook runs after the rendering of the entire UI or


component completes. So when we put an API call in it, the API call
will start after the complete rendering of UI completes that makes
delay in our API call.
so instead of using make api call inside useEffect we go for
useQuery hooks useQuery fetch data as soon as rendering starts so
you don’t have to wait until react loads the entire component.
react query use query not only executes instantly as the page loads
but also handles a lot of things like loading states, error states and
actual data in a single object returned by react query.

Here is an example

// with react query


const { status, data, error, isFetching } = useQuery(
['data'],
async () => {
const data = await (
await fetch(`${API_BASE_URL}/data`)
).json()
return data
}
)

// without react query


useEffect(() => {
try {
setLoading(true)(async () => {
const data = await (await
fetch(`${API_BASE_URL}/data`)).json();
setData(data);
})();
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
}, []);
Crud operation api call?
Following http methods are used for perform CRUD operation
GET – It is a method used for getting Data from a Database.
POST – It is a method used for creating or inserting data into
Database.
PUT – It is a method in which we can update or correct a specific
field of data and then send that updated data to the Database. 
DELETE – It is a method in which we can delete the record or data
of a user from the Database.
Following are such a HTTP Status Codes:
•200 – OK
•201 – Created
•302 – Found
•400 – Bad Request
•401 – Unauthorized
•403 – Forbidden
•404 – Not Found
•500 – Internal Server Error
•502 – Bad Gateway

get last second element from array and while the length of the
array is changeable.

console.log(3+"3")=33
console.log(12-"3")=0

how to manage routes on based on role?


https://github.com/cornflourblue/react-role-based-
authorization-example

what is react memo with example?


React Memo is a higher-order component that wraps around a
component to memoize the rendered output and avoid unnecessary
renderings. This improves performance because it memoizes the
result and skips rendering to reuse the last rendered result.
1) Implement memoization using class component
//Parent.js
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

handleClick = () => {
this.setState((prevState) => {
return { count: prevState.count + 1 };
});
};

render() {
console.log("Parent render");
return (
<div className="App">
<button onClick={this.handleClick}>Increment</button>
<h2>{this.state.count}</h2>
<Child name={"joe"} />
</div>
);
}
}

export default Parent;

//Child.js

class Child extends React.PureComponent { // Here we change


React.Component to React.PureComponent
render() {
console.log("Child render");
return (
<div>
<h2>{this.props.name}</h2>
</div>
);
}
}
export default Child

2) Implement memoization using functional component


//Parent.js
export default function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};

const handler = useCallback(() => { //using useCallback() for the handler function
console.log("handler");
}, []);

console.log("Parent render");
return (
<div className="App">
<button onClick={handleClick}>Increment</button>
<h2>{count}</h2>
<Child name={"joe"} childFunc={handler} />
</div>
);
}

//child.js
export function Child(props) {
console.log("Child render");
return (
<div>
<h2>{props.name}</h2>
</div>
);
}
export default React.memo(Child);

https://www.sitepoint.com/implement-memoization-in-react-to-
improve-performance/
what is mounting and rendering?
Rendering Render() method is the most important method in react.
The render method is only used in the class component. Render()
method is responsible for all the view which is rendered in the
browser. This method returns JSX data with logic code. In fact, it
always returns some value whenever it is null.
Render() method called at the first time of run of the project and
still, the data will be managed as virtual DOM. Re-rendering can
happen multiple times can we count nth times. when content gets
updating of props, a re-rendering method called before any changes
are made to the project is considered as virtual DOM. In the time
the render() method is called and displaying view on the screen.
Mounting is the actual process of transfer the virtual DOM into the
final real DOM. Transfer react element into an actual DOM element
in DOM tree. Mounting means putting elements into DOM.

The life cycle of mounting

There are three phases are :


Mounting:
• constructor():
• getDerivedStateFromProps():
• render():
• componentDidMount():

what is the difference between mapStateToProps() and


mapDispatchToProps() ?

mapStateToProps()
The mapStateToProps() method is used to render the stored data to
the component.

The entirety of the results of the mapStateToProps() method is a


plain object which is later merged into the component’s prop.

mapDispatchToProps()

The mapDispatchToProps() method is used to render the action


creators with props to the component.

In the mapDispatchToProps() method, each action creator is


wrapped in the dispatcher call so that they can be called upon
directly and later merged into the component’s prop.

Manager Round interview questions?

1) Tell me about yourself your previous project and technologies


you are used?
2) How the work was allocated in your team among developers?
3) what are the best performance till now?
4) what the methodology you used for project?
5) what is your daily role in your project?
6) what motivates you to work?
7)explain your job role and current project ?

https://www.w3schools.com/js/js_arrow_function.asp

You might also like