Impors
Impors
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 are slice and splice method what are the difference between
them?
Example of slice
let myArray=[12,23,45,67,89]
let result=myArray.slice(1,4)
Output: [23,45,67]
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)
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);
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 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;
function ExampleOfClosure(){
let a=90;
return function add(){
let b=34;
return a+b;
}
}
let result=ExampleOfClosure();
console.log("---result",result());
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
Benefits of Promises
Improves Code Readability
Better handling of asynchronous operations
Better flow of control definition in asynchronous logic
Better Error Handling
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.
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)
})
})
Example of stopPropagation
function func1(event) {
alert("DIV 1");
event.stopPropagation();
}
Example of setTimeout()
setTimeout(function () {
console.log("Good morning");
}, 2000);
Example of setInterval()
setInterval(function () {
console.log("Good morning");
}, 2000);
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
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
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 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:
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.
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() {
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
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.
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.
App.js
// HOC.js
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
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.
Disadvantages
1. The high pace of development
2. Poor Documentation
3. View Part
4. JSX as a barrier
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 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.
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.
1) useEffect()=>{
2) useEffect()=>{
,[name]} => updating state
3) 2) useEffect()=>{
return ()
,[name]} => unMounting state
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() {
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.
2) Pass the callback function to the child as a props from the parent
component.
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 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.
::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.
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.
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.
nowrap: This is the default value that says the items won’t be
wrapped.
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.
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
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 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.
How to specify the link in HTML and explain the target attribute?
fetch("https://reqres.in/api/users")
.then(res => res.json())
.then(data => console.log(data))
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. &
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.
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
For example :
component ParentComponent1 .
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/
function MyComponent() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setTime(new Date());
}, 1000);
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.
https://www.geeksforgeeks.org/difference-between-useref-and-
createref-in-reactjs/
https://dev.to/andydziabo/how-to-pass-data-between-sibling-
components-in-react-2cjg
•enhancer - Can be used to enhance the Redux store and add third-
The Redux store API is tiny and has only four methods:
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.
Here is an example
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
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>
);
}
}
//Child.js
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.
mapStateToProps()
The mapStateToProps() method is used to render the stored data to
the component.
mapDispatchToProps()
https://www.w3schools.com/js/js_arrow_function.asp