0% found this document useful (0 votes)
3 views73 pages

Fullstack Interview

The document provides an overview of various JavaScript and React concepts, including Babel, controlled vs uncontrolled components, Node.js streams, and the differences between traditional and arrow functions. It explains controlled components as those whose input values are managed by React, while uncontrolled components rely on the DOM for input management. Additionally, it discusses pure functions, pure components, caching strategies, callback hell, and higher-order components in React.

Uploaded by

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

Fullstack Interview

The document provides an overview of various JavaScript and React concepts, including Babel, controlled vs uncontrolled components, Node.js streams, and the differences between traditional and arrow functions. It explains controlled components as those whose input values are managed by React, while uncontrolled components rely on the DOM for input management. Additionally, it discusses pure functions, pure components, caching strategies, callback hell, and higher-order components in React.

Uploaded by

ALIND SHARMA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Q1. What is Babel?

Ans. Babel is a JavaScript compiler that converts modern JavaScript code into a version that is compatible with all
browsers. It is a free and open-source JavaScript transcompiler that converts ECMAScript 2015+ (ES6+) code into
backwards-compatible JavaScript code.

Babel allows web developers to take advantage of the newest features of the language. It enables React developers
to use the latest JavaScript syntax in their components.

Q2. Controlled vs Uncontrolled components in React?


Ans. Controlled and uncontrolled components are just different approaches to handling input from elements in
react.

Feature Uncontrolled Controlled Name attrs

One-time value retrieval (e.g. on submit) ✔️ ✔️ ✔️

Validating on submit ✔️ ✔️ ✔️

Field-level Validation ❌ ✔️ ✔️

Conditionally disabling submit button ❌ ✔️ ✔️

Enforcing input format ❌ ✔️ ✔️

several inputs for one piece of data ❌ ✔️ ✔️

dynamic inputs ❌ ✔️ 🤔

Controlled component: In a controlled component, the value of the input element is controlled by React. We store
the state of the input element inside the code, and by using event-based callbacks, any changes made to the input
element will be reflected in the code as well.

When a user enters data inside the input element of a controlled component, onChange function gets triggered and
inside the code, we check whether the value entered is valid or invalid. If the value is valid, we change the state and
re-render the input element with the new value.

Example of a controlled component:

function FormValidation(props) {

let [inputValue, setInputValue] = useState("");

let updateInput = e => {

setInputValue([Link]);

};

return (

<div>

<form>

<input type="text" value={inputValue} onChange={updateInput} />


</form>

</div>

);

As one can see in the code above, the value of the input element is determined by the state of the inputValue
variable. Any changes made to the input element is handled by the updateInput function.

Uncontrolled component: In an uncontrolled component, the value of the input element is handled by the DOM
itself. Input elements inside uncontrolled components work just like normal HTML input form elements.

The state of the input element is handled by the DOM. Whenever the value of the input element is changed, event-
based callbacks are not called. Basically, react does not perform any action when there are changes made to the
input element.

Whenever use enters data inside the input field, the updated data is shown directly. To access the value of the input
element, we can use ref.

Example of an uncontrolled component:

function FormValidation(props) {

let inputValue = [Link]();

let handleSubmit = e => {

alert(`Input value: ${[Link]}`);

[Link]();

};

return (

<div>

<form onSubmit={handleSubmit}>

<input type="text" ref={inputValue} />

<button type="submit">Submit</button>

</form>

</div>

);

As one can see in the code above, we are not using onChange function to govern the changes made to the input
element. Instead, we are using ref to access the value of the input element.

Q3. What are [Link] Streams?


Ans. [Link]
[Link]
c3fd818530b6
Q4. useCallback() vs useMemo()?
Ans. [Link]
[Link]
useCallback:
 useCallback is used to memoize functions, preventing unnecessary re-renders of
components that depend on those functions.
 It returns a memoized version of the callback function that only changes if one of the
dependencies has changed.
useMemo:
useMemo is used to memoize expensive calculations and prevent re-computation of those
values on every render.
It re-runs the provided function only when one of the dependencies has changed,
otherwise, it returns the memoized value.
Q5. What are the different ways to style a React component?
Q6. a. What is a Pure Function?
Ans. Pure functions are functions that take inputs and return the output value without
affecting any variable outside of their scope. This means they don’t have any side effects on
any of the data outside their scope.
These functions must return a value.
The return value must depend on the input arguments passed.
Q6. b. What is a pure component in react?
Ans. A pure component in React refers to a component that renders the same output given the same props and
state. The idea behind a pure component is that it implements a shallow comparison of props and state to determine
whether the component should update (re-render) or not. If the props or state haven't changed, the component
doesn't re-render, which improves performance by avoiding unnecessary rendering.

While React's PureComponent class provides this functionality for class components, for function components,
we can achieve the same behavior using [Link]().

Pure Component in Terms of Function Components


In React, you can make a functional component pure by wrapping it with [Link](). [Link]() is a
higher-order component (HOC) that performs a shallow comparison of the component’s props. If the props remain
the same between renders, React will skip rendering the component, thus optimizing performance.

How [Link]() Works:


• [Link]() checks whether the props passed to the functional component have changed (using a
shallow comparison).

• If the props are the same as the previous render, the component is not re-rendered.

• If the props are different, the component is re-rendered.

Example of a Pure Functional Component Using [Link]()


javascript
import React from 'react';

// A functional component that will be wrapped in [Link]()


const DisplayValue = ({ value }) => {
[Link]('Component re-rendered!');
return <div>The value is: {value}</div>;
};

// Wrapping the component in [Link]() to make it a pure component


export default [Link](DisplayValue);

Explanation:
• In the above example, the DisplayValue component is wrapped in [Link](), making it a
pure component.

• The [Link]() function checks whether the value prop has changed before re-rendering the
component.

– If the value prop is the same as the previous render, the component will not re-render.

– If the value prop has changed, the component will re-render and update its output
accordingly.

How [Link]() Works Internally:


• [Link]() does a shallow comparison of the props:

– If you pass primitive values like numbers, strings, or booleans, the shallow comparison checks
their equality.

– If you pass objects or arrays as props, [Link]() only checks if the reference to the
object or array has changed (not the values within them).

Example Usage in a Parent Component:


javascript
import React, { useState } from 'react';
import DisplayValue from './DisplayValue';

const ParentComponent = () => {


const [count, setCount] = useState(0);
const [otherValue, setOtherValue] = useState(10);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment Count</button>

{/* This will only re-render if `otherValue` changes */}


<DisplayValue value={otherValue} />
</div>
);
};

export default ParentComponent;

Explanation:
• In the ParentComponent, there's a count state that can be incremented, and a DisplayValue
component that shows the otherValue.

• DisplayValue is wrapped in [Link](), so it will only re-render if the otherValue prop


changes, not when count changes.

• Every time the count is incremented, the ParentComponent re-renders, but since the otherValue
prop is the same, DisplayValue will not re-render.

Shallow Comparison in [Link]():


• [Link]() performs a shallow comparison. It only checks if the references to the props have
changed, not their content.

• For primitive values like numbers and strings, this is sufficient. But for complex objects like arrays and
objects, you should ensure that you pass new references when the data changes, or use a custom
comparison function.

Custom Comparison with [Link]()


You can also provide a custom comparison function to [Link]() if you need more control over how props
are compared.

javascript
export default [Link](DisplayValue, (prevProps, nextProps) => {
// Only re-render if the 'value' prop has changed
return [Link] === [Link];
});

Conclusion:
• A pure component in the context of function components can be created using [Link]().

• It helps prevent unnecessary re-renders by performing a shallow comparison of the component's


props.

• [Link]() is useful for optimizing performance, especially in cases where components receive
large props that do not change often.
This concept aligns with the same principles as pure components in class-based components, which are
implemented using [Link].

Q7. Local Storage vs Cookies?


Ans: [Link]
Q8. Caching Strategies
Q9. Callback Hell?
Ans. setTimeout(() => {
[Link]("First Task");

setTimeout(() => {
[Link]("Second Task")

setTimeout(() => {

[Link]("Third Task")

setTimeout(() => {

[Link]("Fourth Task")

}, 2000)

}, 2000)

}, 2000)

}, 2000)

To avoid callback hell and make the code more readable, you can use Promises and the async/await syntax. Here's
how you can refactor the code:

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const executeTasks = async () => {

await delay(2000);

[Link]("First Task");

await delay(2000);

[Link]("Second Task");

await delay(2000);

[Link]("Third Task");

await delay(2000);

[Link]("Fourth Task");

};

executeTasks();

Q10. What is the difference between Traditional functions and Arrow functions?
Ans:
foo();

bar();

function foo() {
[Link]("I'm a foo()")

}// Function Declaration: Initialized at compile time

const bar = () => {

[Link]("I'm a bar()")

}// Function Expression: Loads only when the interpreter reaches this line

Traditional functions and arrow functions in JavaScript differ in several key aspects, particularly in how they handle
the this keyword, syntax, and use cases. Below are the major differences between them:

1. Syntax
• Traditional Function: The function is declared using the function keyword.

• Arrow Function: Uses the => syntax for a more concise function declaration.
Traditional Function Syntax:

javascript
function traditionalFunction() {
return "This is a traditional function";
}

Arrow Function Syntax:

javascript
const arrowFunction = () => "This is an arrow function";

2. Handling of this
The biggest difference between traditional and arrow functions is how they handle the this keyword.

• Traditional Functions:

– The value of this depends on how the function is called. If a function is called as a method of
an object, this refers to the object. Otherwise, this refers to the global object (window in
browsers).

– Inside a function defined using function, this will change based on context (e.g., it can be
bound dynamically, manually changed using bind(), call(), or apply()).

• Arrow Functions:

– Arrow functions lexically bind this. This means they inherit this from the context in which
they are defined, and it cannot be changed (even using bind(), call(), or apply()).

– This makes arrow functions useful for callbacks and methods where you need to ensure this
refers to the surrounding context.
Example of this in Traditional Function:

javascript
const obj = {
name: "Traditional",
getName: function () {
[Link]([Link]); // 'this' refers to obj
}
};
[Link](); // Output: "Traditional"

const func = [Link];


func(); // Output: undefined, because 'this' refers to global scope or
undefined in strict mode

Example of this in Arrow Function:

javascript
const obj = {
name: "Arrow",
getName: () => {
[Link]([Link]); // 'this' refers to the surrounding lexical scope
(probably undefined or window)
}
};

[Link](); // Output: undefined (since 'this' is inherited from the outer


context, which is not 'obj')

3. arguments Object
• Traditional Functions: The arguments object is available, which contains all the arguments passed to
the function.

• Arrow Functions: Arrow functions do not have their own arguments object. You would need to use
the rest operator ...args to achieve the same behavior.
Traditional Function Example:

javascript
function traditionalFunction() {
[Link](arguments); // 'arguments' contains all passed parameters
}

traditionalFunction(1, 2, 3); // Output: [1, 2, 3]

Arrow Function Example:

javascript
const arrowFunction = (...args) => {
[Link](args); // Must use rest parameter to capture arguments
};

arrowFunction(1, 2, 3); // Output: [1, 2, 3]

4. Constructor Behavior
• Traditional Functions: Can be used as constructors (i.e., with the new keyword), meaning you can
create instances of traditional functions.

• Arrow Functions: Cannot be used as constructors. Attempting to use new with an arrow function will
throw an error.
Traditional Function Constructor Example:

javascript
function Person(name) {
[Link] = name;
}
const person = new Person('Alice');
[Link]([Link]); // Output: Alice

Arrow Function Constructor Example (Error):

javascript
const Person = (name) => {
[Link] = name;
};

const person = new Person('Alice'); // Error: Person is not a constructor

5. No prototype Property
• Traditional Functions: Have a prototype property, which allows them to be used with inheritance
patterns like function constructors.

• Arrow Functions: Do not have a prototype property, so they cannot be used in conjunction with
JavaScript’s prototype-based inheritance.
Example:

javascript
function Traditional() {}
const Arrow = () => {};

[Link]([Link]); // Output: Traditional {}


[Link]([Link]); // Output: undefined

6. Use as Methods
• Traditional Functions: Can be used as methods within objects and have their own this context.

• Arrow Functions: Should not be used as methods inside objects where this refers to the object
itself, because this will not refer to the object as expected (it will refer to the surrounding scope).
Traditional Function Method Example:

javascript
const obj = {
name: "Traditional Method",
getName: function () {
[Link]([Link]); // 'this' refers to obj
}
};

[Link](); // Output: "Traditional Method"

Arrow Function Method Example (Incorrect this behavior):

javascript
const obj = {
name: "Arrow Method",
getName: () => {
[Link]([Link]); // 'this' refers to the outer scope, not the
object
}
};
[Link](); // Output: undefined (because 'this' does not refer to obj)

7. Function Hoisting
• Traditional Functions: Are hoisted, meaning they can be called before they are defined in the code.

• Arrow Functions: Are not hoisted. They must be defined before being invoked.
Traditional Function Hoisting Example:

javascript
sayHello();

function sayHello() {
[Link]("Hello from a traditional function!");
}

Arrow Function Hoisting Example (Error):

javascript
sayHello(); // Error: sayHello is not a function

const sayHello = () => {


[Link]("Hello from an arrow function!");
};

Conclusion:
• Traditional functions provide more flexibility in terms of this binding and are suited for
constructors, object methods, and situations requiring dynamic this.

• Arrow functions are more concise, lexically bind this, and are typically used for short callbacks,
avoiding the need for manual this binding or boilerplate code. However, they are not suited for use
as object methods or constructors.

Q11. What are Higher Order Components?


Ans: [Link]
[Link]
In React, a Higher-Order Component (HOC) is a design pattern where a function takes a component as an argument
and returns a new component with enhanced functionality. HOCs are used to reuse component logic across multiple
components.

A Higher-Order Component is not a part of the React API, but it’s a pattern that emerges from React’s compositional
nature. HOCs are typically used for cross-cutting concerns, such as:

• Code reuse, logic, and bootstrap abstraction

• Render hijacking

• State abstraction and manipulation

• Props manipulation

Characteristics of HOCs:
• HOCs take a component and return an enhanced component.

• They do not modify the original component but create a new one that wraps the original.
• HOCs are commonly used for tasks like authentication, conditional rendering, or handling
performance optimizations.

Syntax of an HOC:
javascript
const withExtraProps = (WrappedComponent) => {
return function EnhancedComponent(props) {
return <WrappedComponent {...props} newProp="Some value" />;
};
};

Example: Higher-Order Component for Logging Props


Let’s say we want to log the props that are being passed to a component. We can create an HOC for this task:

1. Creating the Higher-Order Component:


javascript
import React from 'react';

// Higher-Order Component that logs props


const withLogging = (WrappedComponent) => {
return function EnhancedComponent(props) {
[Link]("Current props: ", props);
return <WrappedComponent {...props} />;
};
};

2. Using the Higher-Order Component:


javascript
import React from 'react';
import withLogging from './withLogging'; // Import the HOC

// Normal functional component


const DisplayData = ({ data }) => {
return <div>Data: {data}</div>;
};

// Wrapping the component with HOC


const DisplayDataWithLogging = withLogging(DisplayData);

const App = () => {


return (
<div>
<h1>Higher-Order Component Example</h1>
<DisplayDataWithLogging data="Hello, World!" />
</div>
);
};

export default App;

Explanation:
1. withLogging is the Higher-Order Component that takes WrappedComponent as an argument.

2. Inside withLogging, we return a new functional component, EnhancedComponent, which logs the
props to the console and renders the original WrappedComponent (DisplayData in this case) with
the passed props.
3. The original component (DisplayData) is wrapped by withLogging to create
DisplayDataWithLogging, which logs the props every time it's rendered.

Another Example: HOC for Conditional Rendering


In this example, we will create an HOC that conditionally renders a component based on a prop.

1. Creating the HOC:


javascript
import React from 'react';

// Higher-Order Component for conditional rendering


const withConditionalRendering = (WrappedComponent) => {
return function EnhancedComponent({ isVisible, ...props }) {
if (!isVisible) {
return <div>Component is hidden</div>;
}
return <WrappedComponent {...props} />;
};
};

2. Using the HOC:


javascript
import React from 'react';
import withConditionalRendering from './withConditionalRendering'; // Import
the HOC

// Normal functional component


const Greeting = ({ message }) => {
return <div>{message}</div>;
};

// Wrapping the component with HOC


const GreetingWithConditionalRendering = withConditionalRendering(Greeting);

const App = () => {


return (
<div>
<GreetingWithConditionalRendering isVisible={true} message="Hello,
User!" />
<GreetingWithConditionalRendering isVisible={false} message="Hello,
User!" />
</div>
);
};

export default App;

Explanation:
1. withConditionalRendering is the Higher-Order Component that checks if the isVisible prop
is true or false.

2. If isVisible is false, it returns a message "Component is hidden". If isVisible is true, it


renders the wrapped component (Greeting).

3. The original Greeting component is wrapped by withConditionalRendering to create


GreetingWithConditionalRendering, which conditionally renders the component based on the
isVisible prop.
Advantages of Higher-Order Components:
1. Code Reusability: HOCs allow you to share logic between components without duplicating code. This
helps avoid code repetition and makes it easier to manage.

2. Separation of Concerns: HOCs help decouple business logic from UI components. You can focus on
building reusable, presentational components while keeping logic in HOCs.

3. Prop Manipulation: HOCs can modify or enhance the props passed to the wrapped component,
allowing you to abstract away details or inject additional data.

Conclusion:
Higher-Order Components (HOCs) in React offer a powerful pattern for code reuse by enhancing components with
additional logic. By wrapping a component, you can add new behaviors, like logging props, conditional rendering, or
handling authentication, without modifying the original component.

Q 12. What is CORS? How does it work?


Ans. CORS, which stands for Cross-Origin Resource Sharing, is a security feature implemented by web browsers to
control how web pages in one domain can request and interact with resources from another domain. This security
measure is in place to prevent potential security vulnerabilities that could arise if a malicious website tries to make
unauthorized requests to a different domain on behalf of a user.

When a web page hosted on one domain makes a request to a server on a different domain, the browser enforces
the Same-Origin Policy by default, which restricts such cross-origin requests. CORS is a mechanism that relaxes this
restriction under controlled conditions, allowing servers to declare which origins are permitted to access their
resources.

Here's a simple example to illustrate how CORS works:

Let's assume you have a web page hosted at [Link] and it needs to make a request to an API hosted at
[Link]

Server-Side Configuration:

On the server hosting the API ([Link] the server needs to include the appropriate CORS
headers in its responses. This is typically done by adding headers like Access-Control-Allow-Origin to specify which
origins are allowed to access the resources.

Example (in a server response header):

Access-Control-Allow-Origin: [Link]

This header tells the browser that requests from [Link] are allowed.

Client-Side Request:

On the client side, when making a request from the web page ([Link] to the API
([Link] the browser checks if the server's CORS headers allow the request. If the server
permits the origin (via the Access-Control-Allow-Origin header), the browser allows the request; otherwise, it blocks
the request.

Example (in JavaScript using the Fetch API):

fetch('[Link]

.then(response => [Link]())

.then(data => [Link](data))

.catch(error => [Link]('Error:', error));

The browser, before allowing the request, checks the CORS headers in the server's response.

It's important to note that CORS is a browser security feature and does not affect non-browser environments like
server-to-server communication. Additionally, the specific CORS headers and configurations may vary depending on
the server technology being used (e.g., Express for [Link], Apache, etc.).

Q 13. What is redux thunk?


Ans. [Link]
Implementing Redux in React:
Redux is a state management library that helps manage and centralize application state. It works with React to
manage complex state logic. We'll explore how to implement Redux in React both with and without middleware like
redux-thunk for asynchronous actions.

Steps to Implement Redux in React (Without Thunk):

1. Install Redux and React-Redux:


You need to install redux and react-redux libraries.

bash
npm install redux react-redux

2. Create a Redux Store:


The store holds the application state. You can only have a single store for a React-Redux app.

javascript
// [Link]
import { createStore } from 'redux';
import reducer from './reducer'; // Your reducer

const store = createStore(reducer);

export default store;

3. Define Reducer(s):
Reducers specify how the application's state changes in response to actions sent to the store.

javascript
// [Link]
const initialState = {
counter: 0,
};

const reducer = (state = initialState, action) => {


switch ([Link]) {
case 'INCREMENT':
return { ...state, counter: [Link] + 1 };
case 'DECREMENT':
return { ...state, counter: [Link] - 1 };
default:
return state;
}
};

export default reducer;

4. Define Action Creators:


Action creators are functions that return action objects.

javascript
// [Link]
export const increment = () => ({
type: 'INCREMENT',
});

export const decrement = () => ({


type: 'DECREMENT',
});

5. Use Provider to Wrap App:


Use the Provider component from react-redux to pass the store to your React components.

javascript
// [Link]
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store'; // Redux store
import App from './App';

[Link](
<Provider store={store}>
<App />
</Provider>,
[Link]('root')
);

6. Connect Components to Redux Store:


Use connect from react-redux to map state and dispatch actions to the component.

javascript
// [Link]
import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from './actions';
const Counter = ({ counter, increment, decrement }) => {
return (
<div>
<h2>Counter: {counter}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};

const mapStateToProps = (state) => ({


counter: [Link],
});

const mapDispatchToProps = { increment, decrement };

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

Implementing Redux in React With Thunk:


When using Redux, handling asynchronous actions like API calls directly can be challenging because Redux only
supports synchronous actions out-of-the-box. redux-thunk middleware allows you to write action creators that
return a function instead of an action. This function can perform asynchronous tasks like fetching data.

1. Install Redux, React-Redux, and Redux-Thunk:


bash
npm install redux react-redux redux-thunk

2. Set Up Redux Store with Thunk:


javascript
// [Link]
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

const store = createStore(reducer, applyMiddleware(thunk));

export default store;

3. Modify Action Creators to Handle Async Logic:


javascript
// [Link]
export const fetchData = () => {
return async (dispatch) => {
dispatch({ type: 'FETCH_REQUEST' });

try {
const response = await
fetch('[Link]
const data = await [Link]();
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', error });
}
};
};
4. Modify the Reducer to Handle Async Actions:
javascript
// [Link]
const initialState = {
data: null,
loading: false,
error: null,
};

const reducer = (state = initialState, action) => {


switch ([Link]) {
case 'FETCH_REQUEST':
return { ...state, loading: true, error: null };
case 'FETCH_SUCCESS':
return { ...state, loading: false, data: [Link] };
case 'FETCH_ERROR':
return { ...state, loading: false, error: [Link] };
default:
return state;
}
};

export default reducer;

5. Use Thunk in Components:


javascript
// [Link]
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchData } from './actions';

const DataComponent = ({ data, loading, error, fetchData }) => {


useEffect(() => {
fetchData();
}, [fetchData]);

if (loading) return <p>Loading...</p>;


if (error) return <p>Error: {error}</p>;
return <div>Data: {data?.title}</div>;
};

const mapStateToProps = (state) => ({


data: [Link],
loading: [Link],
error: [Link],
});

export default connect(mapStateToProps, { fetchData })(DataComponent);

Key Differences Between Redux With and Without Thunk:


1. Without Thunk:

1. Only handles synchronous actions.

2. For async operations, you would typically handle them outside Redux (in components or
services).
2. With Thunk:

1. Allows async actions inside action creators.

2. You can dispatch asynchronous actions and make API calls directly from Redux action creators,
keeping the logic centralized.

Summary:
• Without Thunk: Redux handles synchronous state updates. You dispatch actions, and the reducer
updates the state accordingly.

• With Thunk: You can perform asynchronous tasks (like API calls) in your action creators and dispatch
multiple actions based on the result, such as success or error handling.
This pattern improves the scalability of the application, particularly when dealing with complex asynchronous
workflows in Redux.

Q14. What are web workers?


Ans. [Link]
Q 15. Auth in MERN?
Ans. [Link]
authorization-in-mern-stack-952fa31fe2ae
Q 16. Context API?
Ans. [Link]
Q 17. [Link]() V.S. [Link]()?
Ans. [Link]
Q 18. What is an Immediately Invoked Function (IIFE) in JavaScript?
Ans. An Immediately Invoked Function Expression (IIFE) in JavaScript is a function that is executed immediately
after it is defined. It is a design pattern used to create a local scope for variables, avoiding polluting the global
namespace. This pattern is often used to encapsulate code and create private variables or functions that cannot be
accessed from outside the IIFE.

Syntax of an IIFE:
javascript
(function() {
// Code inside the function
[Link]("This is an IIFE");
})();

In the example above:

• The function is wrapped in parentheses () to turn it into a function expression.

• The final () immediately invokes the function after it is defined.

Detailed Breakdown:
1. Function Expression: The function is wrapped in parentheses to ensure it is treated as an expression
rather than a declaration.

2. Invocation: The () at the end immediately calls the function after it is defined.
Use Cases for IIFE:
1. Avoiding Global Scope Pollution: Variables and functions inside an IIFE are not accessible outside of
it, preventing them from cluttering the global scope.

javascript
(function() {
var privateVariable = "I am private";
[Link](privateVariable); // Accessible inside
})();

// [Link](privateVariable); // Error: privateVariable is not defined

2. Creating a Local Scope: In the pre-ES6 era, JavaScript did not have block-level scope (e.g., let and
const didn't exist), so IIFEs were used to create local scopes.

javascript
(function() {
for (var i = 0; i < 5; i++) {
// `i` is scoped only to this IIFE
}
})();

// i is not accessible here

3. Avoiding Conflicts in Global Namespace: If multiple scripts use common variable names, IIFEs can
prevent conflicts by keeping variables local to each script.

javascript
(function() {
var version = "1.0.0";
[Link]("Script 1 version:", version);
})();

(function() {
var version = "2.0.0";
[Link]("Script 2 version:", version);
})();

IIFE with Parameters:


You can also pass arguments to an IIFE.

javascript
(function(name) {
[Link]("Hello, " + name);
})("John");

IIFE with Arrow Functions (ES6+):


You can also use ES6 arrow functions for IIFEs:

javascript
(() => {
[Link]("IIFE with arrow function");
})();

Conclusion:
IIFEs are a useful pattern in JavaScript for encapsulating code, creating private variables, and avoiding global
namespace pollution. They are particularly handy in legacy code or situations where variable scoping and privacy are
crucial. However, with the advent of ES6 modules and block-scoped variables (let and const), IIFEs are less
commonly used but still relevant in certain contexts.

Q 19. What is Event Emitters in [Link]?


Ans. [Link]
experts-591e3368fdd2
Q 20. Redux workflow?
Ans. [Link]
[Link]
Q 21. Error Boundaries?
Ans. Starting with React 16.6, React introduced the ErrorBoundary component that allows you to use error
boundaries in functional components as well. The ErrorBoundary component is available in the react-error-boundary
library, and you can use it like this:

import { ErrorBoundary } from 'react-error-boundary';

function MyComponent() {

throw new Error('This is an error!');

function ErrorFallback({ error, resetErrorBoundary }) {

return (

<div>

<h2>Something went wrong:</h2>

<pre style={{ whiteSpace: 'normal' }}>{[Link]}</pre>

<button onClick={resetErrorBoundary}>Try again</button>

</div>

);

function App() {

return (

<ErrorBoundary FallbackComponent={ErrorFallback}>

<MyComponent />

</ErrorBoundary>

);

}
export default App;

In the example above, the ErrorBoundary component from react-error-boundary is used to wrap the component
(MyComponent) that might throw an error. The ErrorFallback component is rendered if an error occurs, providing a
way to handle and display the error. The resetErrorBoundary function allows the user to attempt to recover from the
error.

Q 22. Web Workers vs Service Workers.


Ans. [Link]
Q 23. Call, apply and Bind.
Ans. In JavaScript, call, apply, and bind are methods that allow you to control the value of ‘this’ keyword in a
function and, in the case of call and apply, pass arguments to a function. They are often used in the context of
function invocation and provide a way to explicitly set the value of this for a given function.

call Method:

The call method is used to invoke a function with a specified this value and individual arguments.

Syntax: [Link](thisArg, arg1, arg2, ...)

function greet(message) {

[Link](`${message}, ${[Link]}`);

const person = { name: 'John' };

[Link](person, 'Hello');

// Output: Hello, John

apply Method:

The apply method is similar to call but accepts an array-like object as the second argument, where each element in
the array corresponds to an argument of the function.

Syntax: [Link](thisArg, [arg1, arg2, ...])

function greet(message) {

[Link](`${message}, ${[Link]}`);

}
const person = { name: 'Jane' };

[Link](person, ['Hi']);

// Output: Hi, Jane

bind Method:

The bind method returns a new function with a specified this value and, optionally, initial arguments.

Unlike call and apply, bind does not immediately invoke the function; it returns a new function that can be invoked
later.

Syntax: [Link](thisArg, arg1, arg2, ...)

function greet(message) {

[Link](`${message}, ${[Link]}`);

const person = { name: 'Alice' };

const greetPerson = [Link](person);

greetPerson('Hola');

// Output: Hola, Alice

Q 24. Define [Link] event loop.


Ans. [Link]
Q 25. What is Web Pack?
Ans. [Link]
it-8304ecdc3c60/
Q 26. REST vs GraphQL.
Ans. REST (Representational State Transfer) and GraphQL are both API design architectures, but they have different
approaches to how data is requested and delivered. Here's a comparison between REST and GraphQL, along with
examples to illustrate their differences.

REST:

1. Data Fetching:

In REST, each endpoint represents a specific resource, and you request the resource with an HTTP method (GET,
POST, PUT, DELETE, etc.).

Different endpoints are used for different views or representations of the data.

2. Data Shape:
The shape of the response is predefined by the server. Clients receive a fixed structure, and any additional or missing
data requires a new endpoint or modification on the server.

3. Over-fetching and Under-fetching:

Over-fetching: Retrieving more data than needed for a particular view.

Under-fetching: Not getting enough data in a single request, requiring additional requests.

GraphQL:

1. Data Fetching:

In GraphQL, clients specify the shape and structure of the response they need. The client sends a query to the server,
and the server responds with exactly the requested data.

2. Data Shape:

The client defines the structure of the response using the GraphQL query language. The server returns data in the
same structure as requested.

3. Over-fetching and Under-fetching:

GraphQL eliminates over-fetching and under-fetching because clients request only the data they need.

Q 27. What is MicroFrontend?


Ans. A technique for building a modern web app with multiple teams that can ship their respective features
independently.

Q 28. Implicit and Explicit Binding.


Ans. In JavaScript, implicit and explicit binding refer to the way the ‘this’ keyword is determined within a function.
The this keyword is a special variable in JavaScript that refers to the context in which a function is executed. The
binding rules help determine the value of this within a function.

1. Implicit Binding:

Implicit binding occurs when a function is called as a method of an object. In this case, ‘this’ is implicitly set to the
object that owns the method.

const person = {

name: 'John',

greet: function() {

[Link](`Hello, my name is ${[Link]}`);

};

[Link](); // Implicit binding: 'this' refers to the 'person' object

In this example, when [Link]() is called, this is implicitly bound to the person object.

2. Explicit Binding:
Explicit binding occurs when the this value is explicitly set using methods like call(), apply(), or bind().

Q 29. What are Synthetic events in react?


Ans: The synthetic event is essentially a wrapper around the browser’s native event, with
more functions that are useful to prevent native browser behavior (e.g. refreshing a page
after the user clicks a form’s submit button).
I'd be glad to explain synthetic events in React, providing a detailed example:

Synthetic Events

In React, synthetic events are JavaScript objects that encapsulate the browser's native event. They are created by
React when a native event occurs, such as a click, key press, or mouseover. These synthetic events provide a
consistent interface across different browsers, ensuring that your React components can handle events without
worrying about browser compatibility.

Key Features of Synthetic Events:

• Cross-browser compatibility: Synthetic events abstract away the differences between browser
implementations, making it easier to write consistent event handlers.

• Immutability: Synthetic events are immutable, meaning their properties cannot be modified after
they are created. This helps prevent unintended side effects.

• Event bubbling and capturing: Synthetic events support the standard event propagation mechanisms
of bubbling and capturing.

• Additional properties: Synthetic events have additional properties specific to React, such as target,
currentTarget, preventDefault(), and stopPropagation(), which can be used to
manipulate and control event behavior.
Example: Creating a Click Event Handler

Here's a React component that demonstrates how to create a click event handler using synthetic events:

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

function MyComponent() {
const [count, setCount] = useState(0);

const handleClick = (event) => {


setCount(count + 1);
[Link]([Link]); // Access the clicked element
};

return (
<div onClick={handleClick}>
<p>Clicked: {count}</p>
</div>
);
}

export default MyComponent;

In this example:

1. We import useState from React to manage the count state.


2. The handleClick function is defined to handle the click event. It increments the count state and
logs the clicked element to the console.

3. The onClick prop is attached to the div element, passing the handleClick function as its value.

4. When the div is clicked, the handleClick function is called with a synthetic event object as its
argument.

5. Inside the handleClick function, we can access various properties of the synthetic event object,
such as [Link], which refers to the clicked element.
Key Points:

• The onClick prop is used to attach event handlers to elements in React.

• Synthetic events are passed as arguments to event handlers.

• You can access various properties of synthetic events to get information about the event and
manipulate its behavior.

• Synthetic events provide a consistent and cross-browser compatible way to handle events in React.
By understanding synthetic events and how to use them effectively, you can create more robust and interactive React
applications.

Q 30. What are React portals?


Ans. createPortal lets you render some children into a different part of the DOM.
<div>
<SomeComponent />
{createPortal(children, domNode, key?)}
</div>

To create a portal, call createPortal, passing some JSX, and the DOM node where it should
be rendered:
import { createPortal } from 'react-dom';

// ...

<div>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
[Link]
)}
</div>

Q 31. setImmediate() and [Link]() ?


Q 32. Em vs rem?
Ans. I'd be glad to explain the difference between em and rem units in CSS, along with examples:
em:

• Relative unit: The em unit is relative to the font size of the element's parent.

• Dynamic: The size of an element using em units will change if the parent's font size changes.

• Example:

css
.element {
font-size: 1.2em;
}

If the parent element has a font size of 16px, the .element will have a font size of 19.2px (16px * 1.2). If the
parent's font size changes, the .element's font size will also adjust accordingly.

rem:

• Relative unit: The rem unit is relative to the root element's (usually the <html> element) font size.

• Static: The size of an element using rem units will remain constant regardless of changes to the
parent's font size.

• Example:

css
html {
font-size: 16px;
}

.element {
font-size: 1.2rem;
}

In this example, the .element will always have a font size of 19.2px, regardless of the font size of its parent
elements.

Key Differences:

• Relative to: em is relative to the parent's font size, while rem is relative to the root element's font size.

• Dynamic vs. Static: em units are dynamic and change with the parent's font size, while rem units are
static and remain constant.
• Use Cases: em units are often used for creating responsive layouts, where the font size of child
elements scales proportionally to the parent. rem units are typically used for setting base font sizes
and creating consistent typography throughout a website.
Choosing the Right Unit:

The choice between em and rem depends on your specific needs and design goals. If you want to create a responsive
layout where the font sizes scale proportionally to the parent element, em units are a good choice. If you want to
establish a consistent base font size that remains unchanged throughout the website, rem units are more suitable.

Q 33. What is BOM?


Ans. [Link]
I'd be glad to explain the difference between the Browser Object Model (BOM) and the Document Object Model
(DOM) in JavaScript, along with examples:

Browser Object Model (BOM):

• Purpose: Provides information about the browser environment and allows you to interact with it.

• Objects: window, document, location, history, navigator, etc.

• Functionality: Accessing browser properties, manipulating the browser window, navigating history,
and interacting with the user.
Document Object Model (DOM):

• Purpose: Represents the HTML document as a tree structure of objects, providing a way to access and
manipulate its content, structure, and style.

• Objects: Document, Element, Node, Text, Attribute, etc.

• Functionality: Creating, modifying, and removing HTML elements, accessing and setting element
attributes and styles, and handling events.
Key Differences:

Feature BOM DOM

Purpose Browser environment interaction HTML document representation

Objects window, document, location, history, Document, Element, Node, Text,


navigator, etc. Attribute, etc.

Functionality Browser properties, window manipulation, DOM manipulation, element access, attribute and
history navigation, user interaction style modification, event handling

Example:

javascript
// BOM Example:
[Link]("Browser Window Width:", [Link]);
[Link](); // Go back to the previous page

// DOM Example:
const paragraph = [Link]("p");
[Link] = "This is a new paragraph.";
[Link](paragraph);
const heading = [Link]("myHeading");
[Link] = "red";
[Link] = "Modified Heading";

In this example:

• The first line uses the BOM to access the browser window width.

• The second line uses the BOM to navigate back in history.

• The remaining lines use the DOM to create a new paragraph element, append it to the document
body, and modify the style and content of an existing heading element.
In summary:

• The BOM provides a way to interact with the browser environment, while the DOM provides a way to
manipulate the HTML document.

• Both are essential for creating dynamic and interactive web applications.

Q 34. [Link] vs [Link]?


Q 35. What is Event Propagation?
Ans. Event Propagation
Event propagation is the process by which events bubble up or trickle down through the DOM hierarchy in JavaScript.
This means that when an event occurs on an element, it can also be handled by its parent elements or child
elements, depending on the propagation phase.

There are three phases of event propagation:

1. Capture phase: The event starts at the outermost element and travels down to the target element.

2. Target phase: The event reaches the target element (the element where the event originated).

3. Bubbling phase: The event travels back up from the target element to the outermost element.
Example:

html
<div id="outer">
<div id="middle">
<button id="inner">Click me</button>
</div>
</div>

javascript
const outerDiv = [Link]('outer');
const middleDiv = [Link]('middle');
const innerButton = [Link]('inner');

[Link]('click', (event) => {


[Link]('Inner button clicked');
[Link](); // Prevent bubbling
});

[Link]('click', (event) => {


[Link]('Middle div clicked');
});

[Link]('click', (event) => {


[Link]('Outer div clicked');
});

In this example:

1. When the innerButton is clicked, the click event first propagates down from the outerDiv to
the middleDiv and then to the innerButton (capture phase).

2. The click event reaches the innerButton (target phase).

3. The click event bubbles up from the innerButton to the middleDiv and then to the outerDiv
(bubbling phase).
If you click on the innerButton, the following will be logged to the console:

• Inner button clicked

• Middle div clicked

• Outer div clicked


However, if you add [Link]() to the innerButton's event handler, the event will stop
propagating after the innerButton is clicked, and the middleDiv and outerDiv will not handle the event.

Use Cases for Event Propagation:

• Event delegation: Attaching an event handler to a parent element and handling events for its children
to improve performance.

• Custom event propagation: Creating your own event propagation mechanisms for specific use cases.

• Preventing default behavior: Using [Link]() to prevent the browser's default


behavior for certain events (e.g., preventing form submission).
By understanding event propagation, you can effectively handle events in your JavaScript applications and create
more robust and interactive user interfaces.

I'd be glad to explain the difference between event bubbling and event capturing in JavaScript, along with examples:

Event Bubbling:

• Definition: Event bubbling is the process by which events propagate up the DOM hierarchy from the
target element to its parent elements.

• Flow: When an event occurs on an element, it's first handled by that element, and then it's
propagated to its parent element, and so on until it reaches the outermost element.

• Example:

html
<div id="outer">
<div id="middle">
<button id="inner">Click me</button>
</div>
</div>

javascript
const outerDiv = [Link]('outer');
const middleDiv = [Link]('middle');
const innerButton = [Link]('inner');

[Link]('click', (event) => {


[Link]('Inner button clicked');
});

[Link]('click', (event) => {


[Link]('Middle div clicked');
});

[Link]('click', (event) => {


[Link]('Outer div clicked');
});

In this example, if you click on the innerButton, the following will be logged to the console:

– Inner button clicked

– Middle div clicked

– Outer div clicked


Event Capturing:

• Definition: Event capturing is the process by which events propagate down the DOM hierarchy from
the outermost element to the target element.

• Flow: When an event occurs on an element, it's first handled by the outermost element, and then it's
propagated to its child elements until it reaches the target element.

• Example:

javascript
[Link]('click', (event) => {
[Link]('Outer div clicked (capturing)');
[Link]();
}, true);

[Link]('click', (event) => {


[Link]('Middle div clicked (capturing)');
[Link]();
}, true);

[Link]('click', (event) => {


[Link]('Inner button clicked (capturing)');
}, true);

In this example, if you click on the innerButton, the following will be logged to the console:

– Outer div clicked (capturing)

– Middle div clicked (capturing)

– Inner button clicked (capturing)


Key Differences:

• Direction: Event bubbling propagates up the DOM hierarchy, while event capturing propagates down.
• Order: In event bubbling, the target element is handled first, followed by its parent elements. In event
capturing, the outermost element is handled first, followed by its child elements.

• Use Case: Event bubbling is more commonly used, especially for event delegation. Event capturing is
less common and is typically used for specific scenarios where you need to handle events before they
reach the target element.
By understanding the difference between event bubbling and event capturing, you can effectively handle events in
your JavaScript applications and create more robust and interactive user interfaces.

The third argument to addEventListener() determines whether an event will bubble or capture:

• false (default): The event will bubble up from the target element to its parent elements.

• true: The event will capture down from the outermost element to the target element.

Here's an example demonstrating the difference:

javascript
const outerDiv = [Link]('outer');
const middleDiv = [Link]('middle');
const innerButton = [Link]('inner');

// Bubbling
[Link]('click', (event) => {
[Link]('Inner button clicked (bubbling)');
});

[Link]('click', (event) => {


[Link]('Middle div clicked (bubbling)');
});

[Link]('click', (event) => {


[Link]('Outer div clicked (bubbling)');
});

// Capturing
[Link]('click', (event) => {
[Link]('Outer div clicked (capturing)');
[Link](); // Prevent further propagation
}, true);

[Link]('click', (event) => {


[Link]('Middle div clicked (capturing)');
[Link]();
}, true);

[Link]('click', (event) => {


[Link]('Inner button clicked (capturing)');
}, true);

In this example:

• The first three event listeners use the default false argument, so the events will bubble up.

• The last three event listeners use the true argument, so the events will capture down.
When you click on the innerButton, you'll see that the events are handled in different orders depending on
whether they are bubbling or capturing.
Q 36. [Link], [Link], [Link], [Link]?
Ans. [Link]
Q 37. for-of vs for-in array?
Ans. [Link]
a106612cb49
Ans. I'd be glad to explain the differences between for...of and for...in loops in JavaScript, along with
examples:

for...of Loop:

• Purpose: Iterates over the values of iterable objects, such as arrays, strings, and objects with a
[Link] method.

• Syntax:

javascript
for (let value of iterable) {
// Code to be executed for each value
}

• Example:

javascript
const fruits = ['apple', 'banana', 'orange'];

for (let fruit of fruits) {


[Link](fruit);
}

This will output:

apple
banana
orange

for...in Loop:

• Purpose: Iterates over the properties (keys) of an object.

• Syntax:

javascript
for (let property in object) {
// Code to be executed for each property
}

• Example:

javascript
const person = { name: 'Alice', age: 30, city: 'New York' };

for (let property in person) {


[Link](property, person[property]);
}

This will output:

name Alice
age 30
city New York

Key Differences:

• Iteration: for...of iterates over values, while for...in iterates over properties.

• Iterable Objects: for...of works with iterable objects (arrays, strings, etc.), while for...in works
with objects.

• Order: The order of iteration for for...in is not guaranteed, while for...of iterates in the order
of the iterable object's elements.
Choosing the Right Loop:

• Use for...of when you need to iterate over the values of an iterable object.

• Use for...in when you need to iterate over the properties of an object.
Additional Notes:

• Be aware that for...in can iterate over inherited properties, which might not be desirable in all
cases.

• If you need to modify the values of an array while iterating over it, consider using a for loop or the
forEach() method instead of for...of.

By understanding the differences between for...of and for...in loops, you can choose the appropriate loop
for your specific use cases and write more efficient and readable JavaScript code.

Q 38. What are buffers in [Link]?


Ans. [Link]
610b34b98915#:~:text=Simply%20put%2C%20a%20Buffer%20is,raw%20data%20from%20a
%20network.
Q 39. What are middleware?
Ans. [Link]
Q 40. What are stubs?
Ans. In the context of [Link], a "stub" typically refers to a piece of code that acts as a temporary replacement for a
module or function during testing. Stubs are often used in unit testing to isolate the code being tested from its
dependencies.

Here's how stubs work:

1. Temporary Replacement: Stubs replace parts of the code that interact with external dependencies, such as
other modules, databases, or APIs.
2. Controlled Behavior: Stubs allow you to control the behavior of dependencies, making it easier to test
different scenarios without relying on the actual external systems.

3. Isolation: By using stubs, you can isolate the code being tested, ensuring that the test focuses only on its
logic without being affected by external factors.

For example, suppose you have a function that fetches data from an external API. Instead of actually making requests
to the API during testing, you can create a stub that simulates the API's behavior and returns predefined responses.
This allows you to test how your function handles different responses without relying on the actual API.

In [Link], there are various libraries and techniques for creating stubs, including manual stubbing with [Link] or
using mock libraries like Jest's built-in mocking capabilities. These tools provide convenient ways to create stubs and
verify the behavior of your code during testing.

Let's say we have a module that fetches data from an external API using the axios library, and we want to test a
function that depends on this API call.

First, let's create a simple module called [Link]:

// [Link]

const axios = require('axios');

async function fetchDataFromAPI() {

try {

const response = await [Link]('[Link]

return [Link];

} catch (error) {

[Link]('Error fetching data:', error);

throw error;

[Link] = { fetchDataFromAPI };

Now, let's create another module called [Link], which contains a function that processes the data fetched
from the API:

// [Link]

const { fetchDataFromAPI } = require('./dataFetcher');

async function processData() {

try {

const data = await fetchDataFromAPI();


// Process the fetched data here...

return data;

} catch (error) {

[Link]('Error processing data:', error);

throw error;

[Link] = { processData };

To test the processData function without actually making HTTP requests to the external API, we can use a stub.
Here's an example test file using Jest:

// [Link]

const { processData } = require('./dataProcessor');

const { fetchDataFromAPI } = require('./dataFetcher');

[Link]('./dataFetcher'); // Mock the dataFetcher module

describe('processData', () => {

test('should process data correctly', async () => {

// Mock the fetchDataFromAPI function to return a predefined value

[Link]({ some: 'data' });

const result = await processData();

expect(result).toEqual({ some: 'data' });

});

test('should handle errors from fetchDataFromAPI', async () => {

// Mock the fetchDataFromAPI function to throw an error

[Link](new Error('API error'));

await expect(processData()).[Link]('API error');


});

});

Q 41. What are different Async flows?


Ans: [Link]
serial-waterfall-and-queues-6f9c4badbc17

Q 42. What is the difference between class and ID in HTML?


Ans: A Class name can be used by multiple HTML elements, while an ID name must only be
used by one HTML element within the page.
Q 43. Write a file in a local file. What is the difference between writeFile() and
writeFileSync()?

Ans:
The above method is synchronous method of writing on a file.

The below method is asynchronous method of writing on a file =>

Q 44. Write a function that returns a promise after 3s.


Ans
Q 45. What is the output of the following code? Explain.

Ans.
File beginning… and File Ending… are immediately executed as they are synchronous tasks.
The others are put inside a call stack and get executed from there as per the precedence.

Q 46. DOM
Ans [Link]
Q 47. What is Closure?
Ans. This means that a function defined inside another function has access to the variables
and parameters of its outer function, even after the outer function has finished executing.

 Each and every function in JS has access to it’s outer lexical


environment that means it has access to variables and
functions which are in environment of it’s parent.
 Even If this function is executed in some other scope instead
of original scope, it will still remember it’s outer lexical
environment where it was originally present in the code.

function outerFunction() {
var outerVariable = 'I am from outerFunction';

function innerFunction() {
[Link](outerVariable); // innerFunction has access to outerVariable
}

return innerFunction; // returning innerFunction, which forms a closure


}

var myFunction = outerFunction(); // myFunction now holds innerFunction

myFunction(); // when executed, it will print: "I am from outerFunction"

Q 48. PUT vs POST?


Ans. In summary, POST is typically used for creating new resources, while PUT is used for
updating existing resources. POST requests do not require the client to specify the resource
URL and are not idempotent, whereas PUT requests require the client to specify the
resource URL and are idempotent.
Q 49. What is hoisting?
Ans. Hoisting is JavaScript's default behavior of moving declarations to the top of the scope
during the compilation phase.
[Link]
I'd be glad to explain hoisting in JavaScript functions, providing a clear example:

Hoisting in Functions

Hoisting in JavaScript refers to the process where function declarations are moved to the top of their scope (either
global or function scope) before the code is executed. This means that you can call a function before it's declared,
and the interpreter will still be able to find it.

Example:

javascript

greet(); // Output: Hello, world!

[Link](greet); // Output: [Function: greet]

function greet() {
[Link]("Hello, world!");
}

In this example:

1. The greet function declaration is hoisted to the top of the scope.

2. The function call greet() is executed before the function declaration, but it still works because the
function has been hoisted.

3. The [Link](greet) statement prints the greet function itself, showing that it has been
hoisted and is accessible.
Important Notes:

• Function expressions are not hoisted: Only function declarations are hoisted. Function expressions
are not moved to the top of the scope and must be declared before they are used.

• Hoisting is not initialization: Hoisting moves the declaration to the top, but it doesn't initialize the
function's variables or body.

• Scope matters: Hoisting occurs within the scope where the function is defined. If a function is defined
inside a function, it will be hoisted within that inner scope.
Example with Function Expressions:

javascript
greet(); // Output: ReferenceError: greet is not defined

const greet = function() {


[Link]("Hello, world!");
};

In this case, the greet function expression is not hoisted, so calling it before it's declared results in a
ReferenceError.

Understanding Hoisting:

Hoisting is a useful concept to understand in JavaScript, as it helps explain how functions can be called before they
are declared. However, it's important to use hoisting carefully and avoid relying on it for code organization. It's
generally considered best practice to declare functions before using them to improve code readability and
maintainability.

Q 50. Difference between var, const and let.


Ans. [Link]
Q 51. Difference between Clustered and Non-Clustered Indexes.
Ans. Clustered Index is like a Dictionary.
Non-Clustered Index is like a textbook.
[Link]
Q 52. What is a generator function?
Ans. [Link]
Q 53. Spread Vs Rest.
Ans. [Link]
Q54. Destructuring.
Ans. [Link]
Q 55. What is currying?
Ans. [Link]
a2614b82e6ca
Q 56. What is CSS specificity?
Ans. [Link]
Q 57. Explain the difference between visibility: hidden and display: none?
Ans. visibility: hidden hides the element, but it occupies space and affects the layout of the
document.
display: none also hides the element but not occupy space. It will not affect the layout of
the document.
Q 58. What is Event Delegation?
Ans. [Link]
Q 59. What is the use of constructor and super in a class-based components?
Ans. In the code you provided, the constructor and super serve important purposes in setting up the class
component in React. Here's a breakdown:

1. constructor(props)
The constructor is a special method used to initialize a newly created object, including the state and any other
initialization logic. In the context of a React class component, it's where you usually initialize the component's state.

• Why use constructor? The constructor allows you to initialize the component's state with
[Link] = { ... }. In your code, you're setting title to 'Init' in the constructor:

js
[Link] = { title: 'Init' };

• Props handling: The constructor in React takes props as a parameter so you can access
[Link] in the component. While not directly used in your example, it is important when you
want to work with props within the constructor.

2. super(props)
The super keyword is required when you extend a class, in this case, [Link]. It calls the constructor
of the parent class ([Link]) and allows you to access this inside the constructor.

• Why call super(props)? You must call super(props) before accessing this in the constructor. If
you don't, JavaScript will throw an error, as the parent class ([Link]) needs to be
initialized first.
By passing props to super, you allow the parent class to receive the props as well:

js
super(props);

Without super, you won't have access to [Link] within the constructor.

To Summarize:
• constructor(props): Initializes the component's state and binds methods. It takes props to use
them inside the component.

• super(props): Calls the parent class's constructor and gives you access to this and [Link].
It must be called before using this inside the constructor.
In modern React, if you are not using the constructor for any specific logic (like state initialization or method binding),
you can omit it entirely, since [Link] can be initialized directly as a class property.

Q 60. What are the different ways to use useEffect?


Ans. The useEffect hook in React is a powerful tool for managing side effects in functional components. It
replaces lifecycle methods like componentDidMount, componentDidUpdate, and
componentWillUnmount in class components. Below are various ways to use the useEffect hook, along with
explanations:
1. Run on Every Render
The useEffect hook runs after every render by default (both after the initial render and after every update).

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

const Component = () => {


const [count, setCount] = useState(0);

useEffect(() => {
[Link]('This runs after every render');
});

return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

2. Run Only on Mount (ComponentDidMount)


If you want the useEffect to run only once after the component is mounted (similar to componentDidMount),
pass an empty array [] as the second argument. This prevents it from running after updates.

js
useEffect(() => {
[Link]('This runs only once after the component mounts');
}, []);

3. Run on State/Props Change (ComponentDidUpdate)


You can control when useEffect runs by passing specific variables in the dependency array. It will run only when
the values in the array change (similar to componentDidUpdate).

js
useEffect(() => {
[Link]('This runs when count changes');
}, [count]); // Only runs when `count` changes

4. Cleanup on Unmount (ComponentWillUnmount)


You can return a function from useEffect to clean up resources (e.g., subscriptions, event listeners) when the
component unmounts. This is similar to componentWillUnmount.

js
useEffect(() => {
const intervalId = setInterval(() => {
[Link]('Running every second');
}, 1000);

return () => {
clearInterval(intervalId); // Cleanup when component unmounts
};
}, []); // Empty array ensures it runs only once (on mount and unmount)

5. Run on Mount and Cleanup on Props/State Change


If your effect depends on a certain state or prop, the cleanup function will run before the effect runs again when the
dependency changes.
js
useEffect(() => {
[Link](`Subscribed to user with ID: ${userId}`);

return () => {
[Link](`Unsubscribed from user with ID: ${userId}`);
};
}, [userId]); // Effect runs when `userId` changes

6. Async Operations Inside useEffect


Since useEffect cannot handle async functions directly, you need to define an async function inside it if you want
to perform asynchronous tasks like fetching data.

js
useEffect(() => {
const fetchData = async () => {
const result = await fetch('[Link]
const data = await [Link]();
[Link](data);
};

fetchData();
}, []); // Only run once on mount

7. Multiple useEffect Hooks


You can use multiple useEffect hooks in the same component to separate different effects. Each hook works
independently of the others.

js
useEffect(() => {
[Link]('Effect for count');
}, [count]);

useEffect(() => {
[Link]('Effect for userId');
}, [userId]);

8. Debouncing with useEffect


You can use useEffect to handle debouncing (delaying execution of a function to limit how often it runs).

js
useEffect(() => {
const timeoutId = setTimeout(() => {
[Link]('Debounced input:', inputValue);
}, 500);

return () => {
clearTimeout(timeoutId); // Cleanup timeout on each input change
};
}, [inputValue]); // Runs only when `inputValue` changes

Summary:
• No dependency array: Runs on every render.

• Empty dependency array []: Runs only once after the component mounts.

• Specific dependencies [state]: Runs when the specified state or prop changes.
• Return function: Acts as a cleanup function, useful for unmounting or before re-running the effect.
Each use case provides a different lifecycle behavior for functional components, making useEffect versatile and
powerful for handling side effects in React.

Q 61. How to use react-router-dom?


Ans. React Router is a powerful library for handling routing in React applications. It allows you to navigate between
different pages or components in a single-page application (SPA) without reloading the page. Here's a guide on how
to use React Router, covering basic and more advanced usage:

1. Installation
To use React Router, first, install the react-router-dom package:

bash
npm install react-router-dom

2. Basic Setup
Start by setting up the Router component to wrap your entire app. This enables routing throughout your
application.

jsx
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

const Home = () => <h2>Home Page</h2>;


const About = () => <h2>About Page</h2>;

const App = () => {


return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
};

export default App;

Key Components:
• <Router>: The BrowserRouter component wraps the entire app and allows routing.

• <Routes>: Contains all your route definitions (replaces the old Switch component in React Router
v6).

• <Route>: Defines a specific route path and the component to render when that path is visited.

3. Linking Between Pages


Use the Link component to create navigation links without reloading the page.

jsx
import { Link } from 'react-router-dom';

const Navbar = () => (


<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
);

4. Using Dynamic Routes (Route Parameters)


You can define dynamic segments in the URL using route parameters. These can be accessed within the component
via the useParams hook.

jsx
import { useParams } from 'react-router-dom';

const UserProfile = () => {


const { id } = useParams(); // Get the route parameter
return <h2>User Profile ID: {id}</h2>;
};

// In the routes
<Route path="/user/:id" element={<UserProfile />} />

5. Programmatic Navigation with useNavigate


If you need to navigate programmatically (e.g., after a form submission), use the useNavigate hook.

jsx
import { useNavigate } from 'react-router-dom';

const Login = () => {


const navigate = useNavigate();

const handleLogin = () => {


// Perform login logic here...
navigate('/dashboard'); // Redirect after login
};

return <button onClick={handleLogin}>Login</button>;


};

6. Nested Routes
React Router supports nested routing, where a parent component renders child components based on sub-paths.

jsx
const Dashboard = () => (
<div>
<h2>Dashboard</h2>
<Routes>
<Route path="settings" element={<Settings />} />
<Route path="profile" element={<Profile />} />
</Routes>
</div>
);

// In the main Routes


<Route path="/dashboard/*" element={<Dashboard />} />

7. 404 Not Found Route


You can define a catch-all route to handle any unmatched paths, typically used for a "404 Not Found" page.
jsx
const NotFound = () => <h2>404 Not Found</h2>;

<Route path="*" element={<NotFound />} />

8. Protected Routes (Private Routing)


You can implement protected routes that require authentication before allowing access.

jsx
import { Navigate } from 'react-router-dom';

const PrivateRoute = ({ children, isAuthenticated }) => {


return isAuthenticated ? children : <Navigate to="/login" />;
};

// Usage
<Route path="/dashboard" element={<PrivateRoute
isAuthenticated={userLoggedIn}><Dashboard /></PrivateRoute>} />

9. Query Parameters
React Router does not provide built-in query string parsing, but you can handle it using useLocation.

jsx
import { useLocation } from 'react-router-dom';

const Search = () => {


const location = useLocation();
const queryParams = new URLSearchParams([Link]);
const searchTerm = [Link]('q');

return <h2>Search Results for: {searchTerm}</h2>;


};

Example Application
Below is a full example demonstrating multiple features of React Router:

jsx
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Link, useParams, Navigate,
useNavigate } from 'react-router-dom';

// Components
const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;

const UserProfile = () => {


const { id } = useParams();
return <h2>User Profile: {id}</h2>;
};

const Dashboard = () => <h2>Dashboard (Private Route)</h2>;

const NotFound = () => <h2>404 Not Found</h2>;

const PrivateRoute = ({ children, isAuthenticated }) => {


return isAuthenticated ? children : <Navigate to="/login" />;
};
const App = () => {
const isAuthenticated = true; // Mock authentication status

return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/user/1">User Profile</Link>
<Link to="/dashboard">Dashboard</Link>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/user/:id" element={<UserProfile />} />
<Route path="/dashboard" element={<PrivateRoute
isAuthenticated={isAuthenticated}><Dashboard /></PrivateRoute>} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
);
};

export default App;

Summary:
• <Router>: Wraps your app to enable routing.

• <Routes> and <Route>: Define the different routes and which components to render.

• <Link>: Navigates between different routes.

• useNavigate: Programmatically navigate between routes.

• useParams: Access dynamic route parameters.

• PrivateRoute: Handle protected routes based on authentication status.

This setup gives you everything you need to build a basic to advanced routing system in your React app!

Q 62. How to pass data between sibling components using React router?
Ans. Passing data between sibling components in React can be achieved in a few ways, but when you're using React
Router, one effective way is through URL parameters, query parameters, or shared state via a parent component.
Here's how you can handle this:

1. Using a Shared Parent Component


One of the most common and efficient ways to pass data between sibling components is to lift the shared state up to
a common parent component. This parent component can then pass the data as props to the siblings.

Example:
jsx
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-
dom';

const Parent = () => {


const [sharedData, setSharedData] = useState("Initial Data");
return (
<div>
<h1>Parent Component</h1>
<Router>
<nav>
<Link to="/sibling1">Sibling 1</Link>
<Link to="/sibling2">Sibling 2</Link>
</nav>

<Routes>
<Route path="/sibling1" element={<Sibling1 sharedData={sharedData}
setSharedData={setSharedData} />} />
<Route path="/sibling2" element={<Sibling2
sharedData={sharedData} />} />
</Routes>
</Router>
</div>
);
};

const Sibling1 = ({ sharedData, setSharedData }) => {


return (
<div>
<h2>Sibling 1</h2>
<p>Data from Parent: {sharedData}</p>
<input
type="text"
value={sharedData}
onChange={(e) => setSharedData([Link])}
/>
</div>
);
};

const Sibling2 = ({ sharedData }) => {


return (
<div>
<h2>Sibling 2</h2>
<p>Data from Parent: {sharedData}</p>
</div>
);
};

export default Parent;

In this example:

• Parent holds the state (sharedData) and passes it down to both Sibling1 and Sibling2 as
props.

• Sibling1 can update the shared data using the setSharedData function, which will automatically
update Sibling2 since the state is shared.

2. Passing Data Using URL Parameters


Another way to pass data between siblings using React Router is through URL parameters. The first component can
update the route with the data as part of the URL, and the second component can access it via useParams.

Example:
jsx
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Link, useNavigate,
useParams } from 'react-router-dom';

const Sibling1 = () => {


const navigate = useNavigate();

const handlePassData = () => {


navigate('/sibling2/some-data'); // Passing data through the URL
};

return (
<div>
<h2>Sibling 1</h2>
<button onClick={handlePassData}>Pass Data to Sibling 2</button>
</div>
);
};

const Sibling2 = () => {


const { data } = useParams(); // Accessing the data from the URL

return (
<div>
<h2>Sibling 2</h2>
<p>Received Data: {data}</p>
</div>
);
};

const App = () => {


return (
<Router>
<nav>
<Link to="/sibling1">Sibling 1</Link>
</nav>

<Routes>
<Route path="/sibling1" element={<Sibling1 />} />
<Route path="/sibling2/:data" element={<Sibling2 />} />
</Routes>
</Router>
);
};

export default App;

In this example:

• Sibling1 navigates to Sibling2 with some-data passed through the URL.

• Sibling2 accesses that data using the useParams hook from React Router.

3. Using Query Parameters


Another method is to use query parameters to pass data between components. React Router provides access to the
location object, which includes query parameters. You can parse and retrieve these parameters using
useLocation.

Example:
jsx
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Link, useNavigate,
useLocation } from 'react-router-dom';

const Sibling1 = () => {


const navigate = useNavigate();

const handlePassData = () => {


navigate('/sibling2?data=some-query-data'); // Pass data as query
parameter
};

return (
<div>
<h2>Sibling 1</h2>
<button onClick={handlePassData}>Pass Data to Sibling 2</button>
</div>
);
};

const Sibling2 = () => {


const location = useLocation();
const queryParams = new URLSearchParams([Link]);
const data = [Link]('data'); // Get query parameter value

return (
<div>
<h2>Sibling 2</h2>
<p>Received Data: {data}</p>
</div>
);
};

const App = () => {


return (
<Router>
<nav>
<Link to="/sibling1">Sibling 1</Link>
</nav>

<Routes>
<Route path="/sibling1" element={<Sibling1 />} />
<Route path="/sibling2" element={<Sibling2 />} />
</Routes>
</Router>
);
};

export default App;

In this example:

• Sibling1 passes data as a query parameter (?data=some-query-data).

• Sibling2 uses useLocation and URLSearchParams to extract and display the query parameter.

4. Using Context for Global State


When you need more complex data sharing between sibling components or across different levels of the component
tree, React Context is a good solution. This allows you to manage a global state that can be accessed by both sibling
components without having to pass props manually.
Example:
jsx
import React, { createContext, useContext, useState } from 'react';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-
dom';

// Create a context
const DataContext = createContext();

const Parent = () => {


const [sharedData, setSharedData] = useState("Initial Data");

return (
<[Link] value={{ sharedData, setSharedData }}>
<Router>
<nav>
<Link to="/sibling1">Sibling 1</Link>
<Link to="/sibling2">Sibling 2</Link>
</nav>

<Routes>
<Route path="/sibling1" element={<Sibling1 />} />
<Route path="/sibling2" element={<Sibling2 />} />
</Routes>
</Router>
</[Link]>
);
};

const Sibling1 = () => {


const { sharedData, setSharedData } = useContext(DataContext);

return (
<div>
<h2>Sibling 1</h2>
<p>Data from Context: {sharedData}</p>
<input
type="text"
value={sharedData}
onChange={(e) => setSharedData([Link])}
/>
</div>
);
};

const Sibling2 = () => {


const { sharedData } = useContext(DataContext);

return (
<div>
<h2>Sibling 2</h2>
<p>Data from Context: {sharedData}</p>
</div>
);
};

export default Parent;

In this example:
• The DataContext provides the shared state.

• Both Sibling1 and Sibling2 consume the shared state using useContext.

Conclusion:
• Shared Parent State: The most common method for sharing data between siblings.

• URL Parameters: Allows passing data through the route itself.

• Query Parameters: Useful for passing additional data in the URL.

• Context API: Ideal for sharing global state across multiple components without needing to pass props
manually.
Each of these methods has its use case, depending on how persistent or dynamic the data is, and how closely related
the components are.

Q 63. What is the use of useLayoutEffect hook?


Ans. The useLayoutEffect hook in React is similar to useEffect, but it differs in terms of timing when the
effect is executed. It runs synchronously after the DOM updates but before the browser has painted the updates to
the screen, making it useful for tasks that require measuring the DOM and applying changes before the screen
repaints.

Key Differences Between useEffect and useLayoutEffect:


• useEffect: Runs asynchronously after the browser has painted the updates to the screen.

• useLayoutEffect: Runs synchronously after the DOM has been updated but before the browser
has painted the changes. This makes it useful for operations that need to happen before the screen is
rendered to avoid flickering or incorrect measurements.

When to Use useLayoutEffect


You should use useLayoutEffect when you need to make changes that affect the layout or need to measure
something in the DOM before the browser paints it. Examples include:

• Measuring DOM elements: When you need to calculate dimensions, positions, or other layout-related
properties of DOM elements.

• Synchronous visual updates: When you need to make visual changes (e.g., applying animations) that
must happen before the screen is repainted to avoid layout shift or flickering.

• Fixing race conditions: If using useEffect causes visible flicker or incorrect layout, switching to
useLayoutEffect may help ensure the DOM updates are handled synchronously.

Example: Measuring DOM Elements


Here's an example of using useLayoutEffect to measure the width of an element before the browser repaints:

jsx
import React, { useLayoutEffect, useRef, useState } from 'react';

const MeasureComponent = () => {


const [width, setWidth] = useState(0);
const divRef = useRef(null);

useLayoutEffect(() => {
// Measure the width of the element
if ([Link]) {
setWidth([Link]);
}
}, []); // Empty dependency array ensures it runs once after mount

return (
<div>
<div ref={divRef} style={{ width: '50%' }}>
I'm a div with 50% width of the parent.
</div>
<p>Measured width: {width}px</p>
</div>
);
};

export default MeasureComponent;

In this example:

• useLayoutEffect is used to measure the width of the div before the browser renders it to avoid
layout shifts.

• The effect runs synchronously, ensuring that the measured width is accurate and no flickering occurs.

When to Avoid useLayoutEffect


• Performance impact: Since useLayoutEffect runs synchronously and blocks the browser's painting
process until it completes, it can negatively impact performance if the operations inside are slow.

• Non-visual side effects: If your effect doesn't directly affect the layout or need to happen before the
browser renders, it's better to use useEffect, which is asynchronous and non-blocking.

Use Case Scenarios


• Updating layout synchronously: When you need to measure DOM nodes or adjust the layout based
on dimensions or positions.

• Avoiding flicker: If rendering is causing visual flickering or incorrect placement when using
useEffect, you may need to switch to useLayoutEffect to ensure synchronous updates.

• Animations: If you're applying animations or transitioning between different states and want to
prevent layout shifts, you might use useLayoutEffect.

Summary:
• useLayoutEffect is useful when you need to perform DOM-related calculations (like measuring
size) before the browser paints.

• It runs synchronously, blocking rendering until the effect finishes, unlike useEffect, which runs
asynchronously after the paint.

• Use it carefully to avoid performance issues, and only when dealing with layout changes that need to
happen before rendering.
In most cases, useEffect is preferred for asynchronous effects, but useLayoutEffect is your go-to when
layout-related changes need to happen immediately.

Q 64. What are the lifecycle methods of React?

React lifecycle hooks will have the methods that will be automatically called at
different phases in the component lifecycle and thus it provides good control over
what happens at the invoked point. It provides the power to effectively control and
manipulate what goes on throughout the component lifecycle.
For example, if you are developing the YouTube application, then the application will
make use of a network for buffering the videos and it consumes the power of the
battery (assume only these two). After playing the video if the user switches to any
other application, then you should make sure that the resources like network and
battery are being used most efficiently. You can stop or pause the video buffering
which in turn stops the battery and network usage when the user switches to
another application after video play.

So we can say that the developer will be able to produce a quality application with
the help of lifecycle methods and it also helps developers to make sure to plan what
and how to do it at different points of birth, growth, or death of user interfaces.

The various lifecycle methods are:

 constructor():This method will be called when the component is initiated before


anything has been done. It helps to set up the initial state and initial values.
 getDerivedStateFromProps(): This method will be called just before element(s)
rendering in the DOM. It helps to set up the state object depending on the initial
props. The getDerivedStateFromProps() method will have a state as an
argument and it returns an object that made changes to the state. This will be
the first method to be called on an updating of a component.
 render(): This method will output or re-render the HTML to the DOM with new
changes. The render() method is an essential method and will be called always
while the remaining methods are optional and will be called only if they are
defined.
 componentDidMount(): This method will be called after the rendering of the
component. Using this method, you can run statements that need the
component to be already kept in the DOM.
 shouldComponentUpdate(): The Boolean value will be returned by this method which
will specify whether React should proceed further with the rendering or not. The
default value for this method will be True.
 getSnapshotBeforeUpdate(): This method will provide access for the props as well as
for the state before the update. It is possible to check the previously present
value before the update, even after the update.
 componentDidUpdate(): This method will be called after the component has been
updated in the DOM.
 componentWillUnmount(): This method will be called when the component removal
from the DOM is about to happen.

Q 65. What is lazy loading?


Ans. Route-based lazy loading in React allows you to load routes dynamically when the user navigates to them,
which is especially useful for larger applications to improve performance by splitting the bundle.

To implement route-based lazy loading, we use [Link]() to dynamically import the components and
Suspense to provide a fallback while the components are being loaded.

Example: Route-Based Lazy Loading with React Router


jsx
import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

// Lazy load route components


const HomePage = [Link](() => import('./HomePage'));
const AboutPage = [Link](() => import('./AboutPage'));
const ContactPage = [Link](() => import('./ContactPage'));

const App = () => {


return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/contact" element={<ContactPage />} />
</Routes>
</Suspense>
</Router>
);
};

export default App;

Breakdown:
1. Lazy Loading Components:

1. [Link]() is used to lazily load the route components (HomePage, AboutPage,


ContactPage), and they will only be fetched when the user navigates to that route.

js
const HomePage = [Link](() => import('./HomePage'));
const AboutPage = [Link](() => import('./AboutPage'));
const ContactPage = [Link](() => import('./ContactPage'));

2. Suspense Fallback:

1. Suspense is used to show a fallback UI (like a loading spinner) while the lazy-loaded
component is being fetched. It wraps the Routes component in this case.

js
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/contact" element={<ContactPage />} />
</Routes>
</Suspense>

3. Router and Routes:

1. The Router component handles the application's routing, and the Routes component
contains the individual Route components. Each Route specifies a path and the component
to render lazily.

Example of a Lazy-Loaded Component ([Link]):


jsx
import React from 'react';

const HomePage = () => {


return (
<div>
<h1>Welcome to the Home Page</h1>
<p>This is the content of the home page.</p>
</div>
);
};

export default HomePage;

Benefits of Route-Based Lazy Loading:


• Performance Optimization: Only the components related to the current route are loaded, reducing
the initial load time of the app.

• Improved User Experience: The app loads faster because users only download the necessary code for
the current route, and additional code is loaded on demand.

Handling Errors in Lazy-Loaded Routes:


To handle errors, such as if the component fails to load, you can combine Suspense with an Error Boundary.

Example with Error Boundary:


jsx
import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

// Lazy load route components


const HomePage = [Link](() => import('./HomePage'));
const AboutPage = [Link](() => import('./AboutPage'));
const ContactPage = [Link](() => import('./ContactPage'));

// Error boundary to handle lazy loading errors


class ErrorBoundary extends [Link] {
constructor(props) {
super(props);
[Link] = { hasError: false };
}

static getDerivedStateFromError(error) {
return { hasError: true };
}

render() {
if ([Link]) {
return <div>Something went wrong while loading the page.</div>;
}

return [Link];
}
}

const App = () => {


return (
<Router>
<ErrorBoundary>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/contact" element={<ContactPage />} />
</Routes>
</Suspense>
</ErrorBoundary>
</Router>
);
};

export default App;

This ensures that if any error occurs while loading the component, the ErrorBoundary will catch it and display an
error message instead of breaking the entire app.

By using route-based lazy loading, you make your app more scalable, especially for large applications where not all
routes need to be loaded at once. This helps in improving both performance and user experience.

Q 66. Difference between stylesheet and modules in react styling?


Ans. In React, you can apply styles in two primary ways: using a stylesheet (global CSS) or a CSS module. Both have
their pros and cons, but they differ in how they handle scope and class name collision.

1. Stylesheet (Global CSS)


A stylesheet (regular .css file) applies styles globally, meaning that all components in the app can use the classes
defined in the stylesheet. There is no scoping or encapsulation, so class name collisions are possible if multiple
components use the same class name.

Example: Using Global Stylesheet


Global CSS file ([Link]):

css
/* [Link] */
.container {
background-color: lightblue;
padding: 20px;
}

.text {
color: red;
font-size: 20px;
}

React Component ([Link]):

jsx
import React from 'react';
import './[Link]'; // Importing global CSS

const App = () => {


return (
<div className="container">
<h1 className="text">This is a heading</h1>
</div>
);
};

export default App;

Key Points for Stylesheet:


• Global Scope: Classes in the [Link] file are global and can be accessed anywhere in the application,
potentially leading to conflicts or unintended overwrites if two components use the same class name.

• No Isolation: Since the styles are global, you need to be careful with class names to avoid conflicts.
2. CSS Modules (Scoped CSS)
CSS Modules offer a way to scope styles to a specific component. When you use a CSS module, the classes are locally
scoped by default, which prevents class name collisions. CSS Modules automatically generate unique class names
during the build process.

Example: Using CSS Modules


CSS Module file ([Link]):

css
/* [Link] */
.container {
background-color: lightgreen;
padding: 20px;
}

.text {
color: blue;
font-size: 25px;
}

React Component ([Link]):

jsx
import React from 'react';
import styles from './[Link]'; // Importing CSS Module

const App = () => {


return (
<div className={[Link]}>
<h1 className={[Link]}>This is a heading</h1>
</div>
);
};

export default App;

Key Points for CSS Modules:


• Scoped Styles: The styles in [Link] are scoped to the component, and React ensures they
won't conflict with styles in other components.

• Dynamic Class Names: The class names are transformed into unique strings during the build process,
ensuring no collision occurs, even if multiple components use the same class names.

• Cleaner Code: You can reuse common class names (container, text, etc.) without worrying about
conflicts.

Output Example:
• If you're using Global CSS, both .container and .text classes are applied globally. If another
component has classes with the same names, they will affect each other.

• If you're using CSS Modules, each component will have its own unique class names, so .container
in [Link] will only affect that component. Even if another component has a .container
class in its own module, they will not conflict.

Pros and Cons:


Feature Stylesheet (Global CSS) CSS Modules
Scope Global (styles apply throughout the app) Local to the component (scoped styles)

Class Name Possible if the same class names are used in Avoided by unique, dynamically generated class
Collisions different files names

Ease of Use Simple and familiar for smaller projects Slightly more complex setup (need to import
styles as objects)

Reusability Classes can be reused across components Classes are component-scoped, harder to reuse
globally

Maintainability Can lead to conflicts in large projects Better suited for large-scale projects with many
components

Conclusion:
• Global Stylesheet: Useful for small projects or when you want to apply global styles. However, you
need to manage class names carefully to avoid conflicts.

• CSS Modules: Ideal for large-scale projects or when you want to ensure that styles are isolated to
specific components, avoiding conflicts or unintentional overrides. They help keep the code more
modular and maintainable.

Q 67. What are the disadvantages of DynamoDB?


 No support for triggers and server-side scripts.
 No table joins possible.
 Limited querying capabilities.
 Unpredictable costs with spikes in usage.
Q 68. What are DynamoDB Projections
Ans. Projections in DynamoDB refer to the attributes in a table that are projected to the
index. Projections can exclude unnecessary items and reduce the overall size of the payload
returned by the API.
When creating a local secondary index, you must define the projected attributes. Each index
must have at least three attributes: table partition key, index sort key, and table sort key.
Q 69. What is parallel scan in DynamoDB?
Ans. In Dynamoose, which is an elegant, DynamoDB modeling tool for JavaScript, you can perform a parallel scan by
leveraging the parallel option when scanning a DynamoDB table. A parallel scan divides the scan operation into
multiple segments, each processed in parallel, making large table scans more efficient by speeding up the process.

Here's how to implement a parallel scan in Dynamoose using JavaScript:

Step-by-Step Guide to Use DynamoDB Parallel Scan in Dynamoose


1. Install Dynamoose: First, make sure you have Dynamoose installed in your project.

bash
npm install dynamoose
2. Define Your DynamoDB Model: Define your model by creating a schema using Dynamoose. For
example, assume you have a User model.

javascript
const dynamoose = require('dynamoose');

// Define your schema


const userSchema = new [Link]({
id: String,
name: String,
age: Number,
});

// Create the User model


const User = [Link]('User', userSchema);

3. Perform a Parallel Scan: The key to using a parallel scan in Dynamoose is the parallel option. You
need to specify two options: totalSegments (the total number of segments to divide the scan into)
and segment (the segment to scan). The parallel option ensures the scan is divided and executed
in parallel.
Below is an example of a parallel scan with 4 segments:

javascript
const totalSegments = 4; // Total number of segments to divide the scan
const promises = [];

// Loop through each segment and initiate a scan for each


for (let i = 0; i < totalSegments; i++) {
const scanPromise = [Link]()
.parallel({
totalSegments: totalSegments, // Total number of parallel scans
segment: i, // Segment to scan in this iteration
})
.exec(); // Execute the scan

[Link](scanPromise); // Collect each scan's promise


}

// Wait for all the parallel scans to finish


[Link](promises)
.then((results) => {
// Combine all the results into one array
const allResults = [Link]((acc, result) => [Link](result),
[]);
[Link]('All scanned items:', allResults);
})
.catch((error) => {
[Link]('Error during parallel scan:', error);
});

Explanation of the Code:


1. totalSegments: Defines how many segments the scan should be divided into. In this case, we use
totalSegments = 4.

2. segment: i: In each loop iteration, segment specifies which segment of the scan operation this
specific request is handling. The loop runs for each segment.
3. [Link](promises): Runs all the scan promises in parallel and waits for them to finish.

4. Combining Results: Once all scans are complete, the results are combined into a single array.

Considerations:
• Number of Segments: The number of parallel segments should be chosen based on the size of your
table and the available read capacity. More segments will make the scan faster but will use more read
capacity.

• Scan Costs: Scans can be expensive in DynamoDB, especially with large datasets. Consider using a
query when possible, as queries are much more efficient.

Complete Example with Async/Await Syntax:


javascript
const dynamoose = require('dynamoose');

// Define your schema and model


const userSchema = new [Link]({
id: String,
name: String,
age: Number,
});

const User = [Link]('User', userSchema);

// Function to perform parallel scan


const parallelScan = async () => {
const totalSegments = 4; // Number of parallel segments
const promises = [];

// Loop over each segment


for (let i = 0; i < totalSegments; i++) {
[Link](
[Link]()
.parallel({ totalSegments, segment: i }) // Parallel scan
configuration
.exec()
);
}

try {
// Wait for all the scans to complete
const results = await [Link](promises);
// Combine all results
const allResults = [Link](); // Flatten the array of arrays
[Link]('All scanned items:', allResults);
} catch (error) {
[Link]('Error during parallel scan:', error);
}
};

// Execute the parallel scan


parallelScan();

Conclusion:
In Dynamoose, you can perform a parallel scan by dividing the scan into multiple segments using the parallel
option. This improves the performance of scanning large tables in DynamoDB. The above example demonstrates how
to use the parallel scan feature efficiently by distributing the work across multiple segments and combining the
results once all scans are complete.

Q 70. What will be the output of the following code snippet?


const obj1 = {first: 20, second: 30, first: 50};
[Link](obj1);
When an object is passed with duplicate keys, the value of the key will be replaced by the
last value of that key used in the declaration.

Q 71. What will be the output of the following code snippet?

print(typeof(NaN));
NaN in Javascript is defined to be of type number despite its name(not a number).
Q 72. What is the output?
Ans.
var a = [Link]();
var b = [Link]();
print(a);
print(b);
The output of the code will be:
-Infinity
Infinity
Here's why:
1. [Link]() without arguments: When called without any arguments, [Link]()
returns -Infinity. This is because it's looking for the largest number among an empty
set, and by convention, the largest number in an empty set is considered to be -
Infinity.
2. [Link]() without arguments: Similarly, when called without any arguments,
[Link]() returns Infinity. This is because it's looking for the smallest number
among an empty set, and the smallest number in an empty set is considered to be
Infinity.
Q 73. What will be the output of the following code snippet?
(function(){
setTimeout(()=> [Link](1),2000);
[Link](2);
setTimeout(()=> [Link](3),0);
[Link](4);
})();
First the 2 is printed with the [Link], then even with a time delay of 0ms, the 4 is
printed before the 3 because JS executes setTimeout with the Web API, and so the entire
function is executed first. Lastly, after a delay of 2000ms, the 1 is printed.

Q 74. When an operator’s value is NULL, the typeof returned by the unary operator is:
Ans. Any NULL value of operator will always return typeof object.
Q 75. When the switch statement matches the expression with
the given labels, how is the comparison done?
Ans. Switch performs an ‘===’ based comparison, i.e both the value of the expression
and its datatype is compared.

Q 76. What is the output of the following code snippet?


print(NaN === NaN);
In Javascript, NaN is not considered to be equal to NaN even after using the strict equality
operator.
Q 77. What happens when we run npm run build in react app?
Ans. When you run the npm run build command in a React application, it triggers a process to create an
optimized, production-ready build of your application. This command uses the React scripts provided by Create React
App (CRA) to bundle and minify your React app, preparing it for deployment.

Here’s what happens step by step:

1. Creates a build Folder


• The build command compiles the entire React application into static files, which are then stored in a
folder typically called build. This folder contains the files you can deploy to a web server.

2. Bundles JavaScript Files


• All your JavaScript files (including React components, utility functions, etc.) are bundled together into
fewer files (typically main.[hash].js and runtime-main.[hash].js). This reduces the number
of HTTP requests required to load your app.

• These files are also transpiled from JSX/ES6+ syntax to browser-compatible ES5 code using Babel.

3. Minifies JavaScript and CSS


• The build process minifies the JavaScript and CSS files, removing whitespace, comments, and
shortening variable names to reduce file size. This speeds up download times for users.

• Minified code looks smaller and less readable, making it more efficient for production environments.

4. Optimizes Images and Other Assets


• Images, fonts, and other static assets are optimized (e.g., resized, compressed) and copied to the
build directory. This optimization reduces the load times by minimizing asset sizes.
5. Generates Unique Filenames for Caching
• To improve browser caching, filenames are hashed (e.g., [Link]). This ensures that if the
file content changes, the filename will change too, which forces browsers to download the latest
version instead of using a cached version.

• If the app’s source code remains the same, the cached files can be reused, improving page load speed
for returning users.

6. Inlines and Optimizes CSS


• CSS is bundled and minified. If you use CSS-in-JS libraries or CSS Modules, they are also optimized.
Critical CSS might be inlined directly into the HTML to reduce the time to first paint.

7. Creates the [Link] File


• The build process generates a new [Link] file in the build directory. This file serves as the
entry point for your React app.

• It contains a reference to the bundled JavaScript and CSS files, and any other static assets needed for
the app to run.

8. Tree Shaking and Dead Code Elimination


• The build process uses tree shaking to remove any unused code from the final bundle. This ensures
that only the code that is actually used by the application gets included in the output.

• Dead code elimination further removes any code that isn’t needed at runtime.

9. Environment Variables are Set to Production


• The NODE_ENV environment variable is set to production, which ensures that your app runs in the
most optimized and efficient way. This affects how certain libraries (e.g., React) behave, ensuring no
development warnings or unnecessary debug information is included in the final build.

10. Source Maps (Optional)


• The build process can also generate source maps (files like [Link]), which help
developers debug their production code. These maps allow browsers to show the original source code
when debugging, even though the actual code is minified and optimized.

• By default, React’s build process creates source maps, but you can configure this behavior.

Output Example:
Once the npm run build command completes, the build folder typically contains:

/build
/static
/css
[Link]
/js
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

Conclusion:
npm run build prepares your React app for production by bundling, minifying, and optimizing the code, making
it smaller and faster. The result is a set of static files that can be deployed to a web server or a hosting platform, such
as Netlify, Vercel, or AWS S3. This process ensures the app runs efficiently in a production environment.
Q 78. What are the next steps to deploy the above build via s3 and cloudfront?
Ans. Deploying a React app via Amazon S3 and CloudFront is a great way to serve static files efficiently. Here's a
step-by-step guide to deploying your React app:

1. Create an S3 Bucket for Hosting

a. Login to AWS:
• Go to the AWS Management Console and log in.

b. Create a New S3 Bucket:


• Navigate to S3 (under Storage).

• Click on "Create bucket".

• Give your bucket a unique name (e.g., my-react-app-bucket) and select the region closest to your
target audience.

• Uncheck "Block all public access" (since your static files need to be publicly accessible). Confirm this by
acknowledging the warning.

• Enable static website hosting:

– Under Properties, find the Static website hosting option and enable it.

– Set the index document to [Link] (React apps usually have [Link] as their entry
point).

– You can also set a custom error document like [Link], but typically React handles routing
internally.

c. Configure Bucket Permissions:


• Go to the Permissions tab.

• Add a bucket policy that allows public access to the contents:

json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your-bucket-name/*"
}
]
}

Replace your-bucket-name with the actual name of your bucket.

2. Upload the React Build to S3


• Once the build is created (npm run build), upload the contents of the build folder to the S3
bucket:

– Navigate to your S3 bucket in the AWS console.


– Click on the Upload button and select all the files in the build folder (e.g., [Link], CSS,
JS files, etc.).

– Ensure the files are public (based on your bucket policy) so they can be accessed by the web.

3. Create a CloudFront Distribution


To improve performance and security, you can use CloudFront to serve your React app with a content delivery
network (CDN).

a. Navigate to CloudFront:
• In the AWS console, go to CloudFront.

b. Create a New Distribution:


• Click on "Create Distribution".

• Under Origin, choose S3 bucket and select your bucket's endpoint.

• Set the origin access control (OAC) to allow CloudFront to read from your bucket. This enhances
security as users only access content through CloudFront and not directly from S3.

c. Configure Default Cache Behavior:


• For Cache Behavior Settings:

– Set the Viewer Protocol Policy to Redirect HTTP to HTTPS for better security.

– Optionally, configure caching settings based on your requirements.

d. Set Error Pages:


• React apps using client-side routing (e.g., via React Router) need to serve [Link] for all routes.

– In CloudFront, configure a custom error response for 404 errors:

• Set HTTP Error Code to 404 and set Customize Error Response to "Yes".

• For Response Page Path, set /[Link].

• Set the HTTP Response Code to 200.

e. Complete the CloudFront Setup:


• Once you’ve configured all settings, click "Create Distribution".

• CloudFront will provide you with a CloudFront Domain Name (e.g.,


[Link]). This is the URL users will access to view your React app.

4. Invalidate Cache for New Deployments (Optional)


Whenever you deploy a new version of your React app, you may need to invalidate the cache in CloudFront to make
sure users see the latest changes.

a. Invalidate Cache:
• Go to your CloudFront Distribution in the AWS console.

• Click on the "Invalidations" tab.

• Create a new invalidation and set the path to /* to invalidate all the cached files.

5. (Optional) Configure a Custom Domain and SSL


If you want to serve your app with a custom domain and use HTTPS:

a. Register a Domain (if you don’t have one):


• You can use Route 53 (AWS's DNS service) to purchase and manage domains, or use another registrar
like GoDaddy.

b. Add a Custom Domain to CloudFront:


• In the CloudFront Distribution Settings, under Alternate Domain Names (CNAMEs), add your custom
domain (e.g., [Link]).

c. Set Up SSL:
• Request a SSL certificate from AWS Certificate Manager (ACM).

• Choose the region us-east-1 (N. Virginia) for CloudFront.

• Validate the domain either via DNS or email.

• Once validated, configure the CloudFront distribution to use this SSL certificate.

d. Update DNS Records:


• In your DNS settings (e.g., Route 53 or your domain registrar), point your domain (e.g.,
[Link]) to the CloudFront distribution URL (e.g., [Link]).

6. Test the Deployed App


• Now, you can access your React app using either the CloudFront URL (e.g.,
[Link]) or your custom domain (if configured).

• Make sure everything works, especially routes (with React Router) and that all assets are loading
correctly.

Summary of Steps:
1. Create an S3 bucket, enable static website hosting, and upload your build folder.

2. Set up CloudFront as a CDN to serve your static assets.

3. Optionally, configure a custom domain and SSL for HTTPS.

4. Test the deployment and set up invalidation for future updates.


This setup ensures your React app is optimized for speed, security, and scalability, leveraging AWS’s global
infrastructure.

Q 79. What are nodejs streams? Explain with example.


Ans. [Link] streams are an abstraction for working with streaming data. They allow you to read or write data in
chunks (small pieces) instead of loading the entire data into memory at once. This is particularly useful for handling
large files or data from network connections efficiently.

Streams in [Link] can be thought of as a continuous flow of data that can be processed piece by piece.

Types of Streams in [Link]:


1. Readable Streams: These streams allow you to read data chunk by chunk. Examples include file
reading, HTTP requests, or reading from a network socket.

2. Writable Streams: These streams allow you to write data chunk by chunk. Examples include writing to
a file, HTTP responses, or writing to a network socket.

3. Duplex Streams: These streams are both readable and writable. Examples include TCP sockets.
4. Transform Streams: These streams are a special case of Duplex streams where the output is
computed based on the input. An example is the zlib stream for compression.

Key Benefits of Using Streams:


• Memory Efficiency: Instead of loading the entire data into memory, streams handle data in chunks,
which reduces memory consumption.

• Performance: Processing data in smaller chunks improves performance and responsiveness, especially
when dealing with large files or real-time data.

Working with [Link] Streams

1. Readable Stream Example (Reading a file in chunks)


javascript
const fs = require('fs');

// Create a readable stream to read a large file


const readableStream = [Link]('[Link]', {
encoding: 'utf8',
highWaterMark: 16 * 1024, // Set the chunk size to 16KB
});

// Listen for the 'data' event to get chunks of the file


[Link]('data', (chunk) => {
[Link]('New chunk received:', chunk);
});

// Listen for the 'end' event to know when the file is fully read
[Link]('end', () => {
[Link]('File reading finished');
});

// Handle errors
[Link]('error', (err) => {
[Link]('Error reading file:', err);
});

In the above example, the file is read in chunks, and each chunk is processed as soon as it becomes available. This
approach is more memory-efficient than reading the entire file at once.

2. Writable Stream Example (Writing to a file in chunks)


javascript
const fs = require('fs');

// Create a writable stream to write to a file


const writableStream = [Link]('[Link]');

// Write chunks of data to the file


[Link]('Hello, this is the first chunk!\n');
[Link]('This is the second chunk.\n');

// Close the writable stream when done


[Link]('Final chunk to close the file.\n');

// Listen for the 'finish' event to know when writing is done


[Link]('finish', () => {
[Link]('File writing finished');
});
// Handle errors
[Link]('error', (err) => {
[Link]('Error writing to file:', err);
});

3. Pipe Between Streams (Using a readable stream and piping it into a writable
stream)
One common use of streams is to pipe a readable stream directly into a writable stream. For instance, copying a file
without manually handling the chunks:

javascript
const fs = require('fs');

// Create a readable stream for the source file


const readableStream = [Link]('[Link]');

// Create a writable stream for the destination file


const writableStream = [Link]('[Link]');

// Pipe the readable stream into the writable stream


[Link](writableStream);

// Listen for the 'finish' event to know when writing is complete


[Link]('finish', () => {
[Link]('File copied successfully');
});

// Handle errors
[Link]('error', (err) => [Link]('Read error:', err));
[Link]('error', (err) => [Link]('Write error:', err));

In this example, the pipe method automatically reads from the readableStream and writes to the
writableStream without manually managing the chunks. This is a common pattern for streaming operations in
[Link].

Conclusion:
Streams in [Link] provide an efficient way to process data, especially large amounts of it, by handling it in chunks.
Whether you're working with files, network data, or real-time communication, streams help to minimize memory
usage and improve performance.

Summary of Key Points:


• Readable Streams: For reading data (e.g., file reads, HTTP requests).

• Writable Streams: For writing data (e.g., file writes, HTTP responses).

• Duplex Streams: For both reading and writing (e.g., TCP sockets).

• Transform Streams: For data transformation (e.g., zlib compression).


Streams are an essential concept in [Link] for building scalable applications that can handle large volumes of data
efficiently.

Q 80. What are semantic tags and their benefits?


Ans. Semantic tags in HTML are elements that clearly describe their meaning to both the browser and the
developer. They provide additional context about the structure and content of a webpage. Unlike non-semantic tags
like <div> or <span>, which don't give any information about their content, semantic tags have a meaningful
name, making it easier to understand the purpose of the content they enclose.

Examples of Semantic Tags:


• <header>: Defines the header section of a webpage or a section of a document.

• <nav>: Defines a block of navigation links.

• <main>: Represents the main content of the document.

• <article>: Represents an independent piece of content (like a blog post, news article, etc.).

• <section>: Defines sections in a document, such as chapters, headers, or any thematic grouping of
content.

• <aside>: Represents content that is related to the surrounding content but somewhat separate from
the main flow, like sidebars or callouts.

• <footer>: Defines the footer of a document or a section.

• <figure> and <figcaption>: Used to encapsulate media like images, videos, charts, and the
associated captions.

• <mark>: Highlights text.

Benefits of Using Semantic Tags:


1. Improved Accessibility:

1. Semantic tags make it easier for assistive technologies like screen readers to understand the
structure of a webpage. For example, screen readers can easily identify headings, navigation
menus, and footers, allowing users with disabilities to navigate content more efficiently.

2. Better SEO (Search Engine Optimization):

1. Search engines like Google use semantic tags to better understand the content on the page.
For example, content inside an <article> or <section> tag may be treated differently
from generic content inside a <div> tag. This can improve how search engines index and rank
a webpage.

3. Enhanced Readability and Maintainability:

1. Semantic tags make the HTML structure more readable and easier for developers to
understand. A well-structured document helps developers (or future maintainers) to quickly
identify sections of the page, leading to better collaboration and code maintenance.

4. Improved Consistency:

1. Semantic tags help developers create a consistent structure across a website. Instead of using
non-semantic tags (like <div>) with a class or ID for every type of section, developers can use
semantic elements (like <header>, <footer>, etc.), leading to more uniform and predictable
structures.

5. Better Browser Compatibility:

1. Browsers are designed to recognize and handle semantic tags properly, which improves the
rendering of content. Semantic tags also help browsers identify different sections of a
webpage (like headers, footers, navigation bars) and style them more appropriately.
6. Future-Proofing:

1. As HTML evolves, semantic tags are more likely to be supported in future web standards. By
using them, developers ensure that their code remains compliant with modern best practices,
making it easier to update or refactor in the future.

Non-Semantic vs. Semantic Tags Example:


• Non-semantic tags:

html
<div id="header">Welcome to My Website</div>
<div id="nav">Home | About | Contact</div>
<div id="main-content">This is the main content of the page.</div>
<div id="footer">Copyright 2023</div>

• Semantic tags:

html
<header>Welcome to My Website</header>
<nav>Home | About | Contact</nav>
<main>This is the main content of the page.</main>
<footer>Copyright 2023</footer>

In the second example, it is clearer what each section of the page is for, just by looking at the tag names.

Conclusion:
Semantic tags enhance both the user experience and the development process. They improve the accessibility, SEO,
and structure of web pages while making the code easier to understand, maintain, and future-proof. By using
semantic tags, developers can create websites that are more robust, user-friendly, and optimized for search engines.

Q 81. How do I compare two objects in JavaScript?


Ans. [Link]
Q 82. How can I clone an object in JavaScript?
Ans. [Link]
Q 83. What is the difference between using a webpack and using normal npm start in react?
Ans. The key difference between using Webpack and running npm start in React lies in the setup and
configuration:

1. Webpack is a bundler that manually compiles and bundles JavaScript (and other files) into a final
output. It allows custom configurations for optimization, file splitting, and more. You control the build
process by setting up loaders and plugins.

2. npm start in React (via Create React App) uses a preconfigured Webpack under the hood,
abstracting away the setup. It automatically handles development tasks like live reloading, fast builds,
etc.
For custom setups, Webpack offers more flexibility.

Q 84. What are meta tags in html? Explain with example.


Ans. Meta Tags in HTML
Meta tags are HTML elements that provide information about an HTML page. They are placed within the <head>
section of an HTML document and do not directly affect the visible content of the page. Instead, they provide
metadata that can be used by search engines, social media platforms, and other applications.

Common Meta Tags and Their Uses:

• <meta name="description">: Provides a brief summary of the page's content. Search engines
use this to display a short snippet of the page's content in search results.

• <meta name="keywords">: Specifies keywords related to the page's content. While less commonly
used by search engines nowadays, they can still be helpful for SEO.

• <meta name="viewport">: Defines the viewport settings for mobile devices, controlling the page's
scaling and layout. This is crucial for ensuring proper rendering on different screen sizes.

• <meta name="author">: Specifies the author of the page.

• <meta name="robots">: Provides instructions to search engine robots about how to index and
follow the page. For example, you can use noindex to prevent the page from appearing in search
results.

• <meta name="copyright">: Specifies copyright information for the page.

• <meta name="og:title">: Specifies the title of the page that will be displayed on social media
platforms.

• <meta name="og:description">: Specifies the description of the page that will be displayed on
social media platforms.

• <meta name="og:image">: Specifies the URL of the image that will be used as the thumbnail on
social media platforms.
Example:

html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<meta charset="UTF-8">
<meta name="description" content="This is a sample website with meta
tags.">
<meta name="keywords" content="HTML, CSS, JavaScript, web development">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="John Doe">
</head>
<body>
</body>
</html>

In this example, the meta tags provide information about the website's title, description, keywords, viewport
settings, and author. This information can be used by search engines, social media platforms, and other applications
to understand the page's content and display it appropriately.

Q 85. Write LinkedList code in JS?


Ans.
[Link]
5155707685044224/5404274253234176
Q 86.

You might also like