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

Javascript FAQ

This document provides a comprehensive FAQ on JavaScript, covering key concepts such as error handling in asynchronous operations, the differences between synchronous and asynchronous code, callback functions, promises, async/await, hoisting, variable declarations (let, var, const), the event loop, objects, classes, closures, and the differences between using promises and async/await. Each section includes definitions, examples, and explanations to clarify the topics. The content is aimed at enhancing understanding of JavaScript's asynchronous programming model and its various features.

Uploaded by

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

Javascript FAQ

This document provides a comprehensive FAQ on JavaScript, covering key concepts such as error handling in asynchronous operations, the differences between synchronous and asynchronous code, callback functions, promises, async/await, hoisting, variable declarations (let, var, const), the event loop, objects, classes, closures, and the differences between using promises and async/await. Each section includes definitions, examples, and explanations to clarify the topics. The content is aimed at enhancing understanding of JavaScript's asynchronous programming model and its various features.

Uploaded by

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

Javascript - FAQ SET 1

_________________________________________________
__

Q1 : How to catch errors through async?

Errors that occur during an asynchronous operation can be caught using a try-
catch block. Here is an example using async/await:

try {
let result = await asyncFunction();
} catch (error) {
// Handle the error here
}

You can also use the .catch() method to handle errors in promise-based
asynchronous code:

asyncFunction()
.then(result => {
// Do something with the result
})
.catch(error => {
// Handle the error here
});

It's important to note that you should always include a catch block, or use the
.catch() method, to handle any errors that may occur during an asynchronous
operation.

Q2 : Explain your understanding of synchronous and


asynchronous Javascript?

In JavaScript, synchronous code is executed in a blocking manner, meaning


that the script stops and waits for the current task to complete before moving
on to the next task. This type of execution is well-suited for small, simple tasks
that don't take a lot of time to complete.

On the other hand, asynchronous code is executed non-blocking, meaning that


the script does not stop and wait for a task to complete before moving on to
the next task. Instead, it continues to execute the next task, and when the
current task is completed, a callback function is called to handle the result.
This type of execution is well-suited for larger, more complex tasks that may
take a longer time to complete, as it allows the script to continue running
without blocking.

JavaScript uses a concurrency model based on an "event loop" which checks


the message queue for new messages, this way JavaScript can handle multiple
tasks at the same time and non-blocking the main thread.

JavaScript provides several ways to work with asynchronous code, such as


callbacks, promises, and async/await. Callbacks are a simple way to handle
asynchronous code, but they can quickly become difficult to manage and
understand as the codebase grows. Promises and async/await are more
modern and powerful ways to handle asynchronous code, they provide a more
readable and maintainable way of handling asynchronous operations.

Q3 : Explain about Callback Function?

In JavaScript, a callback function is a function that is passed as an argument


to another function and is executed after the outer function has completed its
execution. The callback function is typically used to perform some action or
process the result of the outer function's execution.

A callback function is simply a function that you pass as an argument to


another function. The outer function can then execute the callback function at
some later point. For example, here's a simple function that takes a callback
function as an argument:

function outerFunction(callback) {

// Do some work

callback();

You can then call the outer function and pass in a callback function like this:

outerFunction(function() {

[Link]("Callback executed!");

});
This way you can use the callback function to execute a specific task after the
outer function has finished.
Callbacks are a common pattern in JavaScript, particularly when working with
asynchronous code. Many JavaScript APIs use callbacks to allow developers to
specify what should happen when an asynchronous operation completes. For
example, the setTimeout function takes a callback function as its first
argument, which is executed after the specified time interval has elapsed.
It's important to note that using callbacks can lead to callback hell, which is a
situation where multiple nested callbacks make the code hard to read and
maintain. Promises and async/await are more modern alternatives to
callbacks that provide a more readable and maintainable way of handling
asynchronous operations.

Q4 : Explain your understanding of promises?

In JavaScript, a promise is an object that represents the eventual completion


(or failure) of an asynchronous operation, and its resulting value. A promise is
in one of three states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation completed successfully.
rejected: meaning that the operation failed.
Promises are a more modern and powerful way to handle asynchronous
operations than callbacks. They provide a way to register callbacks for the
successful completion or failure of an asynchronous operation, and also
provide a way to compose multiple asynchronous operations together.
Promises have a then() method that allows you to attach callbacks for when
the promise is fulfilled, and a catch() method that allows you to attach
callbacks for when the promise is rejected. For example,

const myPromise = new Promise((resolve, reject) => {


setTimeout(() => {
resolve("Hello, World!");
}, 1000);
});

[Link]((result) => {

[Link](result); // "Hello, World!"

});

Promises can also be chained together using the then() method, allowing you
to easily compose multiple asynchronous operations together. For example,
you can use then() to create a promise chain that performs multiple
asynchronous operations in sequence:
firstPromise()
.then(secondPromise)
.then(thirdPromise)
.catch(handleError);
Promises also have a static method called all() which allows you to wait for
multiple promises to be fulfilled before continuing.

[Link]([promise1, promise2, promise3]).then((values) => {

[Link](values);

});
Promises are widely supported in modern JavaScript environments and
libraries, and are now a standard feature of the JavaScript language. They
provide a more readable and maintainable way of handling asynchronous
operations than callbacks.

Q5 : Explain about Async await?

Async/await is a more modern and powerful way to handle asynchronous


operations in JavaScript than callbacks or promises. It is built on top of
promises and allows you to write asynchronous code that looks and behaves
like synchronous code.
An async function is a function that is declared with the "async" keyword.
Async functions automatically return a promise, and you can use the "await"
keyword inside an async function to wait for a promise to be fulfilled.
Here is an example of how you can use async/await to handle an asynchronous
operation:
async function example() {

try {
const result = await asyncFunction();
[Link](result);
} catch (error) {
[Link](error);
}
}

The await keyword can only be used inside an async function, and it makes
JavaScript wait until that promise settles and returns its result.
You can also use async/await with [Link]() to wait for multiple promises
to resolve.

async function process() {


const [result1, result2] = await [Link]([promise1, promise2]);
[Link](result1, result2);

Async/await makes it easier to write and read asynchronous code and it's also
more readable and maintainable than using callbacks or chaining promises. It
also allows you to use try-catch blocks to handle errors, similar to synchronous
code.

Q6 : What is hoisting?

In JavaScript, hoisting is a behavior where variable and function declarations


are moved to the top of their scope. This means that variables and functions
can be used before they are declared in the code.
In JavaScript, variable declarations are hoisted to the top of their scope, but
their assignments are not. For example:
[Link](x); // undefined
var x = 5;

This code will output "undefined", not an error, because the variable
declaration "var x" is hoisted to the top of the scope, but the assignment "x =
5" is not.
On the other hand, function declarations are fully hoisted. This means that the
entire function, including its definition, is moved to the top of the scope. For
example:
example(); // Outputs "Hello, World!"
function example() {
[Link]("Hello, World!");
}

This code will output "Hello, World!", because the function declaration is fully
hoisted to the top of the scope and can be called before it is defined in the
code.
It's important to note that variable initializations using let and const,
introduced in ECMAScript 6, are not hoisted like var. They are only accessible
within the block they are defined and not before they are defined.
In summary, hoisting is a behavior in JavaScript where variable and function
declarations are moved to the top of their scope, which allows them to be used
before they are declared in the code. However, variables declared with let and
const are not hoisted in the same way as var.

Q7 : Difference between let, var, const?

In JavaScript, var, let, and const are used to declare variables. The main
difference between these three keywords is the way they handle variable
scoping and reassignment.
var is the oldest way to declare variables in JavaScript, it is function scoped
which means that a variable declared with var inside a function is accessible
within the entire function, including nested functions. If a variable is declared
with var outside a function it becomes a global variable, accessible from
anywhere within your code. Variables declared with var can be re-declared and
re-assigned throughout the entire scope.
let and const were introduced in ECMAScript 6 (ES6) and they are block
scoped which means that a variable declared with let or const inside a block {}
is only accessible within that block. Variables declared with let can be re-
assigned throughout their entire scope, but cannot be redeclared, while
variables declared with const cannot be reassigned or redeclared after they
have been initialized.
In summary:
var is function scoped and can be re-declared and re-assigned throughout the
entire scope.
let is block scoped and can be re-assigned but not re-declared throughout the
entire scope.
const is block scoped and can be initialized only once and cannot be re-
assigned or re-declared.
It's worth noting that let and const are mostly used in modern javascript
development, as they provide more control over variable scoping and
reassignment than var.

Q8 : What is event Loop?

In JavaScript, the event loop is a mechanism that allows the execution of code
to be scheduled, so that a program can continue running while it waits for
other things to happen, such as user input, network responses, or timers to
expire. The event loop is what enables JavaScript to be a single-threaded
language that can still perform non-blocking I/O operations.
The event loop is a continuous process that constantly checks the message
queue for new messages(also called events) and processes them one by one in
the order they were added. Each message typically represents a task that needs
to be completed, such as a function call or an HTTP request.
The event loop has two main parts: the call stack and the message queue.
The call stack is a data structure that keeps track of the execution context of
the program. It stores the function calls that are currently being executed and
the order in which they were called.
The message queue is a data structure that stores the messages that need to be
processed. Each message has an associated callback function that will be
executed when it is processed.
When a function is called, it is added to the call stack and executed. If the
function contains asynchronous code, such as a setTimeout() or an
XMLHttpRequest, the browser will start a timer or initiate a network request.
Once the timer expires or the network request completes, the browser will add
a message to the message queue with the associated callback function to be
executed.
The event loop constantly checks the call stack and message queue. If the call
stack is empty, the event loop will take the first message from the message
queue and add its associated callback function to the call stack. This process
continues indefinitely, allowing the program to continue running and
responding to events even when it is waiting for asynchronous operations to
complete.
In summary, the event loop is a mechanism that allows JavaScript to execute
code in a non-blocking way by scheduling tasks and processing them
asynchronously through a continuous loop that checks the message queue for
new messages and adds them to the call stack to be executed.

Q9 : What is an object

In JavaScript, an object is a data type that represents a collection of properties


and methods. Properties are the values associated with an object, and methods
are the functions that an object can perform.
Objects are created using the object literal notation {} or the object constructor
function Object().
Here is an example of an object created using object literal notation:
const person = {
name: "John Doe",
age: 30,
occupation: "Developer",
sayHello: function() {
[Link](`Hello, my name is ${[Link]}`);
}
};

Properties of an object can be accessed using dot notation


([Link]) or bracket notation
(objectName["propertyName"])
[Link]([Link]); // "John Doe"
[Link](person["age"]); // 30

Methods of an object can be invoked using dot notation or bracket notation


followed by parentheses.

[Link](); // "Hello, my name is John Doe"

JavaScript objects are also known as "dynamic objects" because you can add,
modify, and remove properties and methods at any time after the object has
been created.
Objects in JavaScript are used to store and organize data, encapsulate
functionality, and represent real-world objects in your code. They are also
used to create complex data structures such as arrays and classes.

Q10 : What are classes in js?

In JavaScript, a class is a blueprint for creating objects (instances) with the


same properties and methods. Classes were introduced in ECMAScript 6 (ES6)
as a way to create objects using a more object-oriented programming (OOP)
approach.
A class is defined using the class keyword, followed by the name of the class,
and a pair of curly braces {} which contains the properties and methods of the
class. Here is an example of a simple class definition:

class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
sayHello() {
[Link](`Hello, my name is ${[Link]}`);
}
}

A class also has a special method called a constructor method, which is


automatically called when a new object is created from the class. The
constructor method is used to define and set the initial state of the object.
To create a new object from a class, you use the new keyword, followed by the
name of the class, and parentheses.

const person = new Person("John Doe", 30);


Once an object is created from a class, you can access its properties and
methods using dot notation ([Link] or
[Link]()).

[Link]([Link]); // "John Doe"


[Link](); // "Hello, my name is John Doe"

Classes in JavaScript are a way to create objects using a more structured,


object-oriented approach. They provide a way to define a common structure
for multiple objects, and to encapsulate functionality and data in a single
place. They also provide a way to create objects with a common interface, and
to create new objects that inherit the properties and methods of a parent class.

Q10 : Do you Know about Closures?

Yes, In JavaScript, a closure is a function that has access to the variables and
functions in the scope where it was defined, even after the outer function has
returned. It "closes over" the variables and functions, preserving their state
and making them available for use later.
Here's an example of a closure:
function outerFunction(x) {
return function innerFunction() {
[Link](x);
};
}

const closure = outerFunction(5);


closure(); // logs "5"

In this example, the inner function "closes over" the variable x from the outer
function, preserving its state and making it available for use later, even after
the outer function has returned.
Closures are often used to create private variables and methods in JavaScript,
where a function is returned from another function, and the returned function
has access to the variables and functions in the outer function's scope, but the
outer function's variables and functions are not accessible from the outside.
Closures are also used in event handlers, callbacks, and other asynchronous
code to preserve the context of the function call and allow it to access variables
and functions from the surrounding scope.
Closures are an important concept in JavaScript and they allow you to create
powerful and expressive code. They can be used to create private variables and
methods, to preserve the context of a function call, and to create functions that
can be passed around and executed at a later time.

Q11 : Please tell the difference between using promise vs using


async await?

Promises and async/await are both ways to handle asynchronous operations in


JavaScript, but they are used in slightly different ways.
Promises are a way to handle asynchronous operations by returning an object
that represents the eventual completion (or failure) of an asynchronous
operation, and its resulting value. A promise has a then() method that allows
you to attach callbacks for when the promise is fulfilled, and a catch() method
that allows you to attach callbacks for when the promise is rejected.
For example, you can use a promise to handle an asynchronous operation like
this:

function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("data fetched");
}, 1000);
});
}

fetchData()
.then((data) => {
[Link](data);
})
.catch((error) => {
[Link](error);
});
Async/await is a more recent way to handle asynchronous operations in
JavaScript. It is built on top of promises and allows you to write asynchronous
code that looks and behaves like synchronous code. An async function is a
function that is declared with the "async" keyword. Async functions
automatically return a promise, and you can use the "await" keyword inside an
async function to wait for a promise to be fulfilled.
Here is an example of how you can use async/await to handle an asynchronous
operation:

async function fetchData() {


try {
const data = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve("data fetched");
}, 1000);
});
[Link](data);
} catch (error) {
[Link](error);
}
}

Both promise and async/await are used to handle asynchronous operations,


but async/await provides a more readable and maintainable way of handling
asynchronous operations than callbacks or chaining promises. It also allows
you to use try-catch blocks to handle errors, similar to synchronous code.
In summary, Promises are a way to handle asynchronous operations by
returning an object that represents the eventual completion (or failure) of an
asynchronous operation, and its resulting value. While async/await is a more
recent way to handle asynchronous operations in JavaScript, it is built on top
of promises and allows you to write asynchronous code that looks and behaves
like synchronous code with readability

Q12 : explain null vs undefined?

In JavaScript, both null and undefined indicate the absence of a value, but
they are used in slightly different ways.
undefined is a built-in value that indicates that a variable has been declared
but has not been assigned a value. It is also the default value of function
parameters that are not provided when the function is called.
For example, the following code declares a variable x but does not assign it a
value, so it has the value undefined:
let x;
[Link](x); // undefined
null is a value that represents the intentional absence of any object value. It is
often used to indicate that a variable should have no value.
For example, the following code assigns the value null to the variable x:
let x = null;
[Link](x); // null
In summary, undefined indicates that a variable has been declared but has not
been assigned a value, while null is a value that represents the intentional
absence of any object value.
While using null variable is explicitly set to have no value, undefined is the
default value of variable when it's not defined or has no value assigned to it.
It's worth noting that null is an assignment value, while undefined is a default
value for variables that have not been assigned a value or for function
parameters that are not provided when the function is called.
In terms of comparison, null is considered to be an assignment value, while
undefined is considered as the default value for variables.
In addition, when checking for the existence of a variable or property, it is
generally recommended to use === null or !== null instead of == null or !=
null in order to make the distinction between null and undefined more clear.
In summary, undefined is a built-in value that indicates that a variable has
been declared but has not been assigned a value. null is a value that represents
the intentional absence of any object value, it is often used to indicate that a
variable should have no value. The main difference is that null is an
assignment value and undefined is a default value for variables that have not
been assigned a value or for function parameters that are not provided when
the function is called.

Q13 : What is a prototype?

In JavaScript, the prototype is an object that is associated with each function


and object. It is used to add properties and methods to an object, and to create
a hierarchical relationship between objects.
When an object is created, JavaScript automatically sets its prototype to be the
prototype of its constructor function. This allows the object to inherit
properties and methods from its prototype, and to share common
functionality with other objects that have the same prototype.
Each object has a __proto__ property that points to its prototype, and you
can use this property to access the prototype and its properties.
For example, you can create a Person constructor function, and then use it to
create two objects person1 and person2. Both of these objects will have the
same prototype, which is the prototype of the Person constructor function.
function Person(name) {
[Link] = name;
}
[Link] = function() {
[Link](`Hello, my name is ${[Link]}`);
};

const person1 = new Person("John");


const person2 = new Person("Jane");
[Link](person1.__proto__ === person2.__proto__) // true

You can also add properties and methods to the prototype directly, and they
will be available to all objects that have that prototype.
[Link] = 30;
[Link]([Link]); // 30
[Link]([Link]); // 30

In summary, the prototype is an object that is associated with each function


and object in JavaScript. It is used to add properties and methods to an object,
and to create a hierarchical relationship between objects. Each object has a
__proto__ property that points to its prototype, and you can use this property
to access the prototype and its properties. The prototype is also the
mechanism that allows objects to inherit properties and methods from a
common ancestor.

Q14 : what is output of this code and explain.

var Employee = {
company: 'xyz'
}
var emp1 = [Link](Employee);
delete [Link]
[Link]([Link]);

The output of this code will be "xyz".


This code creates an object Employee with a property company set to "xyz",
and then creates another object emp1 using the [Link]() method, which
sets the prototype of emp1 to be Employee. The delete operator is then used to
remove the company property from emp1.
However, since emp1 has Employee as its prototype, when trying to access the
company property on emp1, it will look for it on the prototype and find it
there, so it will return the value of company on Employee which is "xyz".
It's worth noting that when you use the delete operator on an object, it only
deletes the property from that object and not from the prototype. In this case,
the company property is deleted from emp1 but it still exists on Employee
object, so it can be accessed via prototype.

Q15 : what is output of this code and explain me


[Link](1);
setTimeout(()=> [Link](2), 0);
const myPromise = new Promise((resolve) => resolve())
[Link](() => [Link](3));
[Link](4);

The output of this code will be:


1
4
3
2
This code has four statements:
The first statement [Link](1) is synchronous, it logs the value of 1
immediately.
The second statement setTimeout(()=> [Link](2), 0); creates a timer that
will run the callback function after 0 milliseconds (as soon as possible), but
the callback function is put in the task queue and it will be executed after the
execution stack is empty.
The third statement creates a new promise object and the promise is
immediately resolved and the then function is called, but the then function is
put in the task queue and it will be executed after the execution stack is empty.
The fourth statement [Link](4); is synchronous, it logs the value of 4
immediately.
After the execution stack is empty, the task queue is processed and the
callback of setTimeout and the then function of the promise are executed and
logged their respective values, the order of these two logged values may vary
based on the browser or environment.
In summary, JavaScript is single-threaded, and it processes each statement in
a synchronous manner, but the callbacks of setTimeout and the then function
of the promise are not executed immediately, they are put in the task queue
and executed only after the execution stack is empty.

Q16 : What is Ajax ?

Ajax (Asynchronous JavaScript and XML) is a set of technologies that allows a


web page to communicate with a server and update a part of the page without
refreshing the entire page. It is used to create dynamic and responsive web
applications that can update the content of the page without requiring a full
page reload.
The main technologies used in Ajax are JavaScript and XML, but today, most
developers use JSON (JavaScript Object Notation) instead of XML for data
exchange.
Ajax uses the XMLHttpRequest (XHR) object to exchange data with the
server. The XHR object allows JavaScript to make HTTP requests to the server
and receive responses without reloading the page.
Here is an example of how you can use the XHR object to make an HTTP GET
request to the server and update a part of the page with the response:

const xhr = new XMLHttpRequest();


[Link]("GET", "[Link] true);
[Link] = function() {
if ([Link] === 4 && [Link] === 200) {
const data = [Link]([Link]);
[Link]("content").innerHTML = [Link];
}
};
[Link]();

In this example, the JavaScript code makes an HTTP GET request to


"[Link] and updates the content of the element with the
id "content" with the data received from the server.
Ajax can also be used with more advanced libraries and frameworks such as
jQuery, AngularJS, ReactJS and VueJS, which provide a higher-level
abstraction for making ajax requests and handling the response.
In summary, Ajax (Asynchronous JavaScript and XML) is a set of technologies
that allows a web page to communicate with a server and update a part of the
page without refreshing the entire page, it uses the XMLHttpRequest (XHR)
object to exchange data with the server, it makes it possible to create dynamic
and responsive web applications, it's widely used in modern web development.

Q17 : Difference between find and filter method?

In JavaScript, the find() and filter() methods are both used to iterate through
an array and retrieve specific elements, but they work in slightly different
ways.
The find() method returns the first element in an array that satisfies a given
condition. It takes a callback function as an argument, which is called for each
element in the array, and returns the first element for which the callback
function returns true.
Here's an example of how you can use the find() method to find the first
element in an array that is greater than 10:

const numbers = [1, 2, 3, 4, 5, 11, 12, 13];


const firstLargeNumber = [Link](number => number > 10);
[Link](firstLargeNumber); // 11

The filter() method, on the other hand, returns an array of all the elements in
the original array that satisfy a given condition. It also takes a callback
function as an argument, which is called for each element in the array, and
returns an array of all the elements for which the callback function returns
true.
Here's an example of how you can use the filter() method to find all elements
in an array that are greater than 10:
const numbers = [1, 2, 3, 4, 5, 11, 12, 13];
const largeNumbers = [Link](number => number > 10);
[Link](largeNumbers); // [11, 12, 13]

In summary, The find() method is used to find the first element that satisfies a
given condition, while filter() method is used to find all elements that satisfy a
given condition and return them as an array.

Q18 : how to find any key in array of objects

To find a specific key in an array of objects, you can use the filter() method in
combination with the [Link]() method. The [Link]() method returns
an array of a given object's own enumerable property names, which can be
used to check if a specific key exists in the object.
Here's an example of how you can use the filter() method to find all objects in
an array that have a specific key:

const arrayOfObjects = [
{name: 'John', age: 30, city: 'New York'},
{name: 'Jane', age: 25, city: 'Los Angeles'},
{name: 'Mike', age: 35, city: 'Chicago'},
{name: 'Emily', age: 28}
];

const filteredObjects = [Link](object =>


[Link](object).includes('city'));
[Link](filteredObjects);

In this example, the filter() method is used to iterate through the


arrayOfObjects and for each object, [Link](object) is used to get an array
of all the object's own enumerable property names, the includes('city') is then
used to check if the array of keys includes the key 'city' and if yes, the object is
included in the filtered array.
You can also use some() method in place of includes() like this:

const filteredObjects = [Link](object =>


[Link](object).some(k => k === 'city'));

In summary, to find a specific key in an array of objects, you can use the
filter() method in combination with the [Link]() method to iterate
through the array, for each object check if the array of keys returned by
[Link](object) includes the specific key you're looking for and if it does,
include that object in the filtered array.

Q19 : Why is javascript a single threaded language?

JavaScript is a single-threaded language because it can only process one task


at a time. This means that it can only execute one line of code at a time, and it
does this in a linear, sequential manner.
There are several reasons why JavaScript is single-threaded:
1. JavaScript was originally designed to be a simple scripting language for
web browsers. At the time, web browsers were not capable of running
multiple threads, so JavaScript was designed to work within this
limitation.
2. Single-threaded execution simplifies the programming model and
makes it easier for developers to reason about their code. When code
runs in a single thread, it is guaranteed to execute in a predictable order,
and it is less likely to encounter race conditions or other concurrency-
related issues.
3. JavaScript's single-threaded nature makes it easier to work with the
Document Object Model (DOM), which is the interface used to
manipulate web pages. Because the DOM is also single-threaded,
JavaScript can interact with it without the need for complex thread
synchronization mechanisms.
4. JavaScript's event-driven model is based on the idea of an event loop,
which is a mechanism that handles the execution of code in response to
events such as user input, network requests, and timers. Because the
event loop is single-threaded, it can handle multiple events and execute
their corresponding code in a predictable order.
To summarize, JavaScript is single-threaded because it was designed to work
within the limitations of web browsers at the time, it simplifies the
programming model and makes it easier for developers to reason about their
code, it makes it easier to work with the DOM and enables the event-driven
model that is based on the idea of an event loop.

Q20 : Explain about when you'll use call, bind and apply?

In JavaScript, the call(), bind() and apply() methods are used to change the
context of a function, also known as "binding" the function to a specific
context.
The call() method invokes a function with a given context and arguments
passed in individually. The first argument passed to the call() method is the
context that the function should be invoked with, and the remaining
arguments are passed as individual arguments to the function.
Here's an example of how you can use the call() method to change the context
of a function:

const person = { name: "John" };

function sayName() {
[Link](`My name is ${[Link]}`);
}

[Link](person); // My name is John

The apply() method is similar to the call() method, but it takes the context and
arguments as an array. It invokes a function with a given context and
arguments passed in as an array.
Here's an example of how you can use the apply() method to change the
context of a function:

const person = { name: "John" };

function sayName(surname) {
[Link](`My name is ${[Link]} ${surname}`);
}

[Link](person, ["Smith"]); // My name is John Smith

The bind() method creates a new function with the same body and scope as the
original function, but with the context set to the first argument passed to
bind().
Here's an example of how you can use the bind() method to change the context
of a function:

const person = { name: "John" };

function sayName() {

[Link](My name is ${[Link]});


}
const boundSayName = [Link](person);
boundSayName(); // My name is John
In this example, the `bind()` method creates a new function
`boundSayName` with the same body and scope as the original `sayName`
function, but with the context set to the `person` object. When the
`boundSayName` function is invoked, it will have the context of `person` and
will log "My name is John".

In summary, `call()` method allows you to invoke a function with a given


context and arguments passed in individually, while `apply()` method is
similar to call but it takes the context and arguments as an array, whereas
`bind()` method creates a new function with the same body and scope as the
original function, but with the context set to the first argument passed to
`bind()`.

You would use `call()` or `apply()` when you want to invoke a function and
immediately change its context, whereas `bind()` is useful when you want to
create a new function with a specific context that can be invoked later.
Javascript - FAQ SET 2
_____________________________________________
__

Q1 : Differences and use local, session and cookie storage?


Local storage, session storage, and cookies are all ways to store data in a
user's browser, but they have some key differences.

Local storage allows you to store data on the user's device permanently,
until the user manually clears it. This means that the data will still be
available even if the user closes the browser or restarts their device.
Session storage, on the other hand, only stores data for a single browser
session. The data is deleted when the user closes the browser or restarts
their device.

Cookies are small text files that are stored on the user's device by the
website. They are used to remember the user's preferences or activity on
the website. Cookies are sent back to the server with each request, which
allows the website to maintain state. Cookies have a size limit of 4KB and
have expiration time.

In general, you would use local storage if you need to store data
permanently, and session storage or cookies if you only need to store
data temporarily.

Q2 : explain about Data types in javascript?

JavaScript has several built-in data types, including:


1. Number: used for numeric values, including integers and floating-
point numbers.
2. String: used for text values.
3. Boolean: used for true/false values.
4. Undefined: used when a variable has been declared but has not
been assigned a value.
5. Symbol: used to create unique and immutable identifiers.
6. Object: used to store collections of data and functions.

JavaScript also has two special data types:


1. null: represents a null or empty value.
2. NaN: represents a "not a number" value.
JavaScript is a dynamically-typed language, which means that variables
do not have a fixed data type. The same variable can hold values of
different data types during the execution of a program.
JavaScript also has a typeof operator which is used to check the data type
of a variable. It returns a string indicating the type of the variable.

For example,
let x = 10;
[Link](typeof x); // "number"

let y = "hello";
[Link](typeof y); // "string"

let z = true;
[Link](typeof z); // "boolean"

JavaScript also has a new operator called instanceof which is used to


check the type of an object, it returns a boolean indicating whether the
object is an instance of the specified constructor.
For Example,

let x = new Array();


[Link](x instanceof Array); // true
[Link](x instanceof Object); // true

Q3 : how does react convert jsx to vanilla js?


React converts JSX to vanilla JavaScript using a transpiler, such as
Babel.
When a React application is built, the JSX code is transformed into
JavaScript code that can be understood by the browser. This process is
known as transpilation. The transpiler, such as Babel, will parse the JSX
code and convert it into equivalent JavaScript code, which can be
understood by the browser.

For example, this JSX code:

const element = <h1>Hello, world!</h1>;

Will be transpiled to this JavaScript code:

const element = [Link]("h1", null, "Hello, world!");


In the transpiled JavaScript, [Link] is used to create a
virtual DOM node that represents the JSX element. The first argument is
the type of the element, the second argument is the properties of the
element and the rest are the children of the element.
When the JavaScript code is executed, React uses this virtual DOM to
update the actual DOM, which is what the user sees in the browser. This
process is known as "reconciliation" and it ensures that the DOM is
updated efficiently, only changing the elements that need to be updated.
So, React converts JSX to vanilla JavaScript using transpilation and this
conversion allows React to work efficiently with the DOM and update the
UI in an efficient way.

Q4 : Explain all array methods available in javascript?

Here are some commonly used array methods in JavaScript:


1. concat(): combines two or more arrays into a single array.
2. every(): checks if every element in an array pass a test.
3. filter(): creates a new array with elements that pass a test.
4. find(): returns the first element that passes a test.
5. forEach(): executes a function for each element in an array.
6. join(): converts an array to a string, with a separator between
elements.
7. indexOf(): returns the first index at which an element can be
found.
8. map(): creates a new array with the results of a function for each
element.
9. pop(): removes the last element from an array and returns it.
10. push(): adds one or more elements to the end of an array and
returns the new length.
11. reduce(): applies a function to reduce an array to a single value.
[Link](): reverses the order of elements in an array.
[Link](): removes the first element from an array and returns it.
[Link](): extracts a part of an array and returns it as a new array.
15. sort(): sorts the elements of an array in place.
[Link](): adds or removes elements from an array.
17. toString(): returns a string representation of an array.
18. unshift(): adds one or more elements to the front of an array
and returns the new length.
[Link](): checks if any element in an array passes a test.

Note that not all methods are available in all versions of JavaScript, and
your exact usage may vary depending on the version you are using.
Q5 : What are the features added in ES6?

ECMAScript 6 (ES6), also known as ECMAScript 2015, is a version of


JavaScript that was released in 2015. It introduced several new features
and improvements to the language. Some of the main features added in
ES6 include:

1. Arrow functions: a shorthand for defining anonymous functions,


with a more concise syntax.
2. Classes: a new way to define object-oriented classes and
constructors.
3. Template literals: a new way to create string templates, with
support for string interpolation.
4. Destructuring: a new way to extract data from arrays or objects
and assign it to variables.
5. Default parameters: a way to specify default values for function
parameters.
6. Spread operator: a way to expand arrays and objects and pass them
as separate arguments to a function.
7. Rest parameters: a way to gather remaining arguments into an
array.
8. Promises: a new way to handle asynchronous code, to make it
easier to write and reason about.
9. Modules: a new way to organize and share JavaScript code,
including support for imports and exports.
10. let and const: new ways to declare variables, with block-level
scope and immutability.

These are some of the main features added in ES6. There are many more
features and enhancements, such as Symbols, Iterators, Generators, and
more. These new features help developers to write more efficient and
maintainable code, and makes JavaScript more powerful.

Q5 : Explain about Arrow function?

Arrow functions, also known as "fat arrow" functions, are a shorthand


syntax for defining anonymous functions in JavaScript. They were
introduced in ECMAScript 6 (ES6) and are a more concise way to write
function expressions.
Here is an example of an anonymous function defined using the
traditional function keyword:

let add = function (a, b) {


return a + b;
}
And here is the same function defined using an arrow function:

let add = (a, b) => {


return a + b;
}

Arrow functions have several key features:

1. They have a shorter syntax than traditional function expressions.


2. They do not bind their own this, arguments, super, or [Link]
values.
3. They are always anonymous.

A few more examples of arrow function are

let double = (x) => x * 2;


let greet = () => [Link]("Hello World!");
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = [Link](x => x * 2);

Arrow function are very useful in array methods like map, filter, reduce
etc and they are also useful when you are passing function as a
parameter.

Arrow functions can be very useful in simplifying your code and making
it more readable and maintainable.

Q6 : Difference between javascript, react and typescript?

JavaScript, React, and TypeScript are all technologies related to web


development, but they serve different purposes:

 JavaScript is a programming language that is widely used to create


interactive websites, as well as to build server-side applications
and mobile apps using frameworks like [Link]. JavaScript is
supported by all web browsers and is the de facto standard for
client-side web development.
 React is a JavaScript library for building user interfaces. It was
developed by Facebook and is now maintained by a community of
developers. React allows developers to create reusable UI
components and manage the state of an application. It uses a
virtual DOM that optimizes the performance of web applications.
 TypeScript is a superset of JavaScript, which adds optional types
and other features to the language. It was developed by Microsoft
and is now an open-source project. TypeScript is designed to
improve the development experience by providing better tooling
and catching errors early. It can also be used to build large-scale
applications, with features like interfaces and classes.

In summary, JavaScript is a programming language, React is a library


for building user interfaces, and TypeScript is a superset of JavaScript
that adds optional types and other features to improve the development
experience.

React and TypeScript can be used together to build web applications.


React allows developers to build reusable components and manage the
state of an application, while TypeScript provides better tooling and
catching errors early.

Q7 : explain all events and onclick functionality?

JavaScript allows you to add interactivity to web pages by using events.


Events are actions or occurrences that happen in the browser, such as a
button being clicked, a page being loaded, or a user moving the mouse
over an element.
Here are some common events in JavaScript:

 click: Triggered when an element is clicked.


 mousedown: Triggered when a mouse button is pressed down on
an element.
 mouseup: Triggered when a mouse button is released on an
element.
 mousemove: Triggered when the mouse is moved over an element.
 mouseover: Triggered when the mouse pointer enters an element.
 mouseout: Triggered when the mouse pointer leaves an element.
 keydown: Triggered when a key is pressed down on the keyboard.
 keyup: Triggered when a key is released on the keyboard.
 submit: Triggered when a form is submitted.
 load: Triggered when a page or an image is fully loaded.
 resize: Triggered when the browser window is resized.
 scroll: Triggered when the document view is scrolled.

onclick is a JavaScript function that is used to add a click event to an


element. It is used to execute a function when an element is clicked.
Here's an example of how to use the onclick function:
<button onclick="alert('Button clicked!')">Click me</button>

In this example, when the button is clicked, the alert function will be
called and the message "Button clicked!" will be displayed.

You can also use the addEventListener method to attach an event to an


element.

let button = [Link]("myBtn");


[Link]("click", function(){
alert("Button clicked!");
});

This method is more flexible as you can attach multiple events to the
same element and also you can remove events using
removeEventListener method.

These are just some examples of how events and onclick functionality
can be used in JavaScript. There are many other types of events and
ways to handle them, but these are the most common.

Q8 : How does async and defer work?

In HTML, async and defer are attributes that can be used to load
external scripts (JavaScript files) asynchronously.

The async attribute tells the browser to load the script asynchronously,
which means that it will download the script file in the background while
the page continues to load. Once the script is downloaded, it will be
executed immediately. This can improve the performance of a page by
allowing it to load faster. However, it can also cause issues if the script
relies on other resources or elements that haven't loaded yet.

The defer attribute tells the browser to load the script asynchronously,
but to only execute it once the page has finished loading. This can be
useful for scripts that don't need to run immediately, but should be
executed after the page has loaded.
Here's an example of how to use the async attribute:

<script async src="[Link]"></script>

And here's an example of how to use the defer attribute:


<script defer src="[Link]"></script>

When both async and defer are present, defer will take precedence.
By default, script tags block the rendering of the page, it means the
browser will not render the page until the script is fully downloaded,
parsed and executed. Using async or defer allows the browser to
continue parsing and rendering the page while the script is being
downloaded, parsed, and executed in the background.

If you're using a library like jQuery, then it's usually recommended to use
the defer attribute, as it will ensure that jQuery is loaded and ready to
use before any scripts that rely on it are executed.

In summary,
 async attribute tells the browser to download the script file in the
background while the page continues to load, and execute the
script immediately.
 defer attribute tells the browser to download the script file in the
background while the page continues to load, and execute the
script only after the page is fully loaded.

Q9 : What is debouncing and throttling?

Debouncing and throttling are techniques used to limit the number of


times a function or event is executed in a given period of time.

Debouncing is a technique in which multiple function calls are


consolidated into a single call, executed after a certain period of time has
passed without any new calls being made. This is useful in situations
where a rapid succession of events (such as a user typing quickly) would
otherwise cause a function to be executed multiple times, wasting
resources and potentially causing unexpected behavior.

Throttling is similar to debouncing, but instead of waiting for a period of


time to pass before executing the function, it limits the number of times
the function can be executed within a given period of time. This is useful
in situations where you want to limit the rate at which a function is
executed (for example, to prevent a server from being overwhelmed with
requests).
Both debouncing and throttling are used to improve the performance
and responsiveness of a user interface, by preventing unnecessary
function calls and limiting the rate at which functions are executed.

Q10 : What is temporal deadzone?

Temporal dead zone (TDZ) is a concept in JavaScript that refers to a


period of time during which certain variables or function bindings are
not accessible.
In JavaScript, variables declared with the let or const keywords are not
accessible until they are initialized. This means that if a variable is
declared with let or const and then accessed before it is initialized, an
error will be thrown. The period of time between the variable declaration
and initialization is known as the temporal dead zone.

For example, if you declare a variable with let x; and then try to access
the variable before it is initialized, you will get a ReferenceError .

[Link](x); // ReferenceError: x is not defined


let x;

TDZ is also applicable on function binding with let or const keyword. If a


function is declared with let or const and then accessed before it is
initialized , an error will be thrown.

f(); // ReferenceError: x is not defined


let f = function() { [Link]('Hello'); }

TDZ is a feature of JavaScript that is intended to help developers catch


errors early, by ensuring that variables and functions are properly
initialized before they are used.

Q11: Difference between for in & for of loop?

for...in and for...of are both looping constructs in JavaScript, but they are
used for different purposes and have some key differences.

A for...in loop is used to iterate over the enumerable properties of an


object. It will iterate over all enumerable properties, including those that
are inherited from the object's prototype.

let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
[Link](key + ': ' + obj[key]);
}
// Output:
// a: 1
// b: 2
// c: 3

A for...of loop is used to iterate over the values of an iterable object, such
as an array or a string. It does not iterate over properties of an object,
instead it iterates over the values of the object.

let arr = [1, 2, 3];


for (let val of arr) {
[Link](val);
}
// Output:
// 1
// 2
// 3

for...of loop is not just limited to arrays, it can also be used with any
other object that implements the iterable interface.

In summary, for...in is used to iterate over the properties (keys) of an


object, while for...of is used to iterate over the values of an iterable
object.

Q12 : what is setTimeout? How does it work ?

setTimeout() is a JavaScript function that allows you to schedule a


function to be executed after a specified amount of time has passed. It is
a method of the window object, which is the global object in the browser.

The basic syntax of setTimeout() is as follows:

setTimeout(function, delay);

The function argument is the function that you want to execute after the
specified delay. The delay argument is the amount of time, in
milliseconds, that you want to wait before executing the function.

For example, the following code will log "Hello, World!" to the console
after a delay of 2 seconds (2000 milliseconds):

setTimeout(() => { [Link]("Hello, World!") }, 2000);


setTimeout() works by adding the specified function to the browser's
JavaScript event queue. The function is not executed immediately, but
instead waits in the queue until the specified delay has passed. Once the
delay has passed, the function is removed from the queue and executed.

It's worth noting that when setTimeout is called, it returns an ID of the


timeout which can be used to clear the timeout using clearTimeout(id)
function.

setTimeout() is often used in conjunction with other JavaScript


functions and event-handling code to create timed events and effects in
web pages, such as delayed form submissions, timed animations, and
more.

Q13 : Task - you need to add items in div through a input box ?

Here's an example of how you might add items to a div element through
an input box using JavaScript:
HTML:

<div id="container"></div>
<input type="text" id="input-box">
<button id="add-button">Add</button>

JavaScript:

const container = [Link]("container");


const inputBox = [Link]("input-box");
const addButton = [Link]("add-button");

// Add event listener to the add button


[Link]("click", function() {
// Get the value of the input box
const value = [Link];
// Create a new div element
const newDiv = [Link]("div");
// Set the text content of the new div to the value of the input box
[Link] = value;
// Append the new div to the container div
[Link](newDiv);
// clear the input box
[Link] = ""
});
In this example, the div element with the id "container" will act as a
container for the items to be added. The input box is used to gather the
text to be added to the container and a button is used to trigger the
adding of an item to the container.
When the add button is clicked, the value of the input box is captured, a
new div element is created with the text content set to the value of the
input box and it is appended to the container div.
You can further style the divs as per your requirements.

Q14 : Explain Javascript object vs json?

JavaScript objects and JSON (JavaScript Object Notation) are both used
to represent data in JavaScript, but they have some key differences.

A JavaScript object is a collection of key-value pairs, where the keys are


strings and the values can be any data type (strings, numbers, booleans,
objects, etc.). Objects are created using curly braces {} and properties are
separated by commas.

const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};

JSON, on the other hand, is a lightweight data-interchange format that is


easy for humans to read and write and easy for machines to parse and
generate. It is based on a subset of the JavaScript Programming
Language and its text format is a way of representing JavaScript objects
and arrays in a string format.

{
"firstName": "John",
"lastName": "Doe",
"age": 30
}

The main difference between a JavaScript object and JSON is that a


JavaScript object can have methods (functions), while JSON can only
have key-value pairs. JSON also requires keys to be enclosed in double-
quotes, while JavaScript objects do not.
It is possible to convert a JavaScript object to JSON using
[Link](object) method and JSON to JavaScript object using
[Link](json) method.

In summary, JSON is a text-based format for representing JavaScript


objects, while a JavaScript object is an actual object in JavaScript. JSON
is typically used for transferring data between a server and a web
application, while JavaScript objects are used within a program to
represent and manipulate data.

Q15 : What will be the output and Explain approach of the code?

for(var i=0;i<10;i++) {
setTimeout(function() {
[Link](i);
}, 1000)
}

The output of the code you provided would be the numbers 10 10 10 10


10 10 10 10 10 10, each logged to the console one second apart.

The approach used in this code is to use a for loop to iterate from 0 to 9,
and within each iteration, a setTimeout function is called with a callback
function that logs the current value of the loop variable i to the console.
However, the problem with this approach is that since the setTimeout
function is asynchronous, all the callbacks are invoked after the for-loop
has completed, so the value of i is always 10, the last value when the loop
completed, so the output will be 10 10 10 10 10 10 10 10 10 10 instead of
0123456789

You can use let instead of var or IIFE(immediately invoked function


expression) to solve the problem.

here is one way to correct the output so that it logs the numbers 0
through 9 as expected

for(var i=0;i<10;i++) {
(function(i) {
setTimeout(function() {
[Link](i);
}, 1000 * i)
})(i);
}
In this version, an IIFE (immediately invoked function expression) is
used to create a new scope for each iteration of the loop, so each callback
function has access to its own copy of the variable i, rather than sharing
the same global variable. The function passed to setTimeout is invoked
after the given time delay, passing the correct value of i to the inner
function, which then logs that value to the console.

Alternatively, you can use let instead of var, as let is block scoped
variable and var is function scoped variable.

for(let i=0;i<10;i++) {
setTimeout(function() {
[Link](i);
}, 1000 * i)
}

This will also give the correct output of 0 1 2 3 4 5 6 7 8 9.

Q16 : Do you know callback hell ?

Yes, "callback hell" is a term used to describe a situation where a


program has a large number of nested callback functions, making the
code difficult to read and understand. This can happen when using
asynchronous programming techniques, such as those used in
JavaScript, where a function is passed as an argument to another
function and is only executed after some event occurs.

When many asynchronous operations are performed one after the other,
the code can become deeply nested and difficult to follow. This is often
referred to as "callback pyramid" or "callback hell". It can be difficult to
reason about the flow of control, and it becomes hard to locate bugs.

Promises and async/await are introduced to handle callback hell and


make the code more readable.
Promises provide a way to handle async operations in a more structured
way, allowing developers to chain together async operations in a way
that is similar to synchronous code.

With the introduction of async/await, it becomes much easier to write


and read asynchronous code that is easy to reason about. It makes the
code look like synchronous code, but under the hood it's still
asynchronous.

Q17 : How to fetch data from json file?


There are several ways to fetch data from a JSON file in JavaScript, but
one common way is to use the fetch() function. The fetch() function
allows you to make network requests similar to XMLHttpRequest
(XHR).

Here's an example of how you might use fetch() to load data from a local

JSON file:

fetch('[Link]')

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

.then(data => {

// do something with the data

})

.catch(error => {

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

});

In this example, the fetch() function is used to make a request to the

specified [Link] file. The then() method is used to parse the response

as JSON and return a JavaScript object. The data returned from the file

can then be used in the next then callback function.

If there is any error in fetching the file it will be caught by the catch

block.

Alternatively, you can use XMLHttpRequest() object to fetch the json

file, an example would be like this:


var xhr = new XMLHttpRequest();
[Link]('GET', '[Link]', true);
[Link] = 'json';
[Link] = function() {
if ([Link] === 200) {
var data = [Link];
// do something with the data
}
};
[Link]();

This code creates a new instance of the XMLHttpRequest object, opens a


GET request to the specified JSON file, sets the response type to JSON,
and then waits for the onload event to fire. Once the data is loaded, it can
be used within the onload callback function.

Please note that both of these examples assume that the JSON file is
hosted on the same domain as the JavaScript file. If the file is hosted on
a different domain, you'll need to configure the server to allow cross-
origin resource sharing (CORS) in order to fetch the file.

Q18 : What if the fetch api fails?

If the fetch() API fails, it will reject the promise with a TypeError or a
FailedFetchError and the catch() block will be executed. The catch()
block is used to handle any errors that occur during the fetch operation,
such as a network error or a failure to parse the response.

In the example I provided in my previous answer, the catch() block logs


the error to the console using [Link](). You can also handle the
error by displaying a message to the user or redirecting them to an error
page.

The catch() block will only be executed if the fetch request fails, such as
when the server is down or the internet connection is lost. If the request
is successful but the response has a non-2xx status code, the promise will
be resolved, but the [Link] property will be false. You can check the
response status and handle it accordingly:

fetch('[Link]')
.then(response => {
if (![Link]) {
throw new Error(`HTTP error, status = ${[Link]}`);
}
return [Link]();
})
.then(data => {
// do something with the data
})
.catch(error => {
[Link]('Error:', error);
});

Also, note that the fetch() API is relatively new and not all browsers
support it. If you need to support older browsers, you may need to use an
older API like XMLHttpRequest or a library like axios or jQuery.

Q19 : write pseudo code of swap two numbers without using temporary
variable in Js?

Here is an example of how you might swap the values of two variables a
and b in JavaScript without using a temporary variable:

// Initial values of a and b


a = 10;
b = 20;

// Swapping the values of a and b


a = a + b; // a = 10 + 20 = 30
b = a - b; // b = 30 - 20 = 10
a = a - b; // a = 30 - 10 = 20

// Final values of a and b


[Link](a); // 20
[Link](b); // 10

In this example, the values of a and b are swapped by using the following
three steps:

Adding the values of a and b and storing the result in a


Subtracting the original value of b from a and storing the result in b
Subtracting the new value of b from a and storing the result in a.

This approach uses the mathematical properties of addition and


subtraction to swap the values of a and b without the need for a
temporary variable. It can be used to swap values of any number of
variables.
Please note that this is a pseudo-code, in practice you don't need to use
[Link] and can just swap the variables.
Q20 : What do you understand about "strictmode" in Javascript?

"strict mode" is a feature of JavaScript that allows you to place a


program or a function in a "strict" operating context. This means that
some of the JavaScript's "unsafe" features are disabled and certain errors
will throw in strict mode which would have been ignored in non-strict
mode. This helps to catch and prevent errors in your code, and makes it
easier to write secure and high-quality code.

When you use strict mode, you must use the string "use strict" at the
beginning of a file (global scope) or a function.

For example:

"use strict";
// code here will run in strict mode

Or

function example() {
"use strict";
// code here will run in strict mode
}

Here are some of the features that are changed or disabled in strict
mode:

 Variables that are declared but not initialized will not be created as
properties of the global object.
 The value of 'this' is undefined in function in strict mode.
 It prohibits the use of some of the less-than-ideal language features
and practices.
 It makes it impossible to accidentally create global variables.
 It eliminates some silent type-conversion errors.
It makes certain assignments that were previously allowed to throw
errors.
It disallows the use of 'eval' and 'arguments' as variable or function
names.

Strict mode is not recommended to be used in production code as it can


break some existing code and make it difficult to debug. But it is useful
while developing and testing the code.
Please note that strict mode only affects the code in the scope it is
declared, it doesn't affect the code in the other scopes.
HTML & CSS - FAQ SET 1
_______________________________________________

Q1 : Can you create a HTML form for both students and teachers
where upon submission, the data will be displayed in a table?

<html>
<head>
<title>Student and Teacher Form</title>
</head>
<body>
<form id="form">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>
<label for="role">Role:</label>
<select id="role" name="role">
<option value="student">Student</option>
<option value="teacher">Teacher</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
<br><br>
<table id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Role</th>
</tr>
</table>
</body>
<script>
const form = [Link]("#form");
const table = [Link]("#table");

[Link]("submit", (event) => {


[Link]();

const name = [Link]("#name").value;


const age = [Link]("#age").value;
const role = [Link]("#role").value;
const newRow = [Link]();
[Link]().innerHTML = name;
[Link]().innerHTML = age;
[Link]().innerHTML = role;
});
</script>
</html>

When the form is submitted, the JavaScript event listener will trigger and
prevent the default form behavior. It will then retrieve the values from the
form fields and add a new row to the table with the data.

Q2 : Difference between link and anchor tag?

The <a> (anchor) tag is used to create a hyperlink to another web page or to a
specific location within the same page. The <a> tag has two main attributes:
href and name. The href attribute specifies the URL of the page or resource to
link to, while the name attribute is used to create a named anchor for linking
to a specific location within the same page.

The <link> tag, on the other hand, is used to specify relationships between the
current document and other resources, such as stylesheets, icons, and
alternate versions of the document. The <link> tag is typically used within the
<head> section of an HTML document and has attributes such as rel, href,
and type.

In summary, the <a> tag is used for creating hyperlinks to other pages or
within the same page, while the <link> tag is used for specifying relationships
between the current document and other resources.

Q3 : When to add script tag in head and When to do it in body?

The placement of the <script> tag in an HTML document can affect how the
JavaScript code within it is executed.

Generally, it is recommended to include the <script> tag in the <head> section


of the document if the JavaScript code is needed for setting up the structure of
the page or needs to be executed before the page has finished loading.

On the other hand, if the JavaScript code is related to a specific part of the
page or needs to be executed after the page has finished loading, it is
recommended to include the <script> tag just before the closing </body> tag.
This ensures that the page has finished loading and the necessary elements are
in place before the JavaScript code is executed.

In addition, you can also include the <script> tag with the async or defer
attribute to specify how the script should be loaded and executed. These
attributes can help optimize the loading of the page and avoid potential issues
with executing the JavaScript code too early or too late.

Q4 : what are attributes in HTML ?

Attributes in HTML are additional values that provide more information or


specific instructions to an HTML element. Attributes are specified within the
opening tag of an HTML element, and they take the form of name-value pairs.

For example, the src attribute in an <img> element provides the source URL
of the image to display, while the href attribute in an <a> element specifies the
URL of the linked page.

Some common attributes include:

 class: used to apply CSS styles to an HTML element


 id: used to identify a specific element and apply styles or JavaScript to it
 src: used to specify the source URL for elements like <img> and
<script>
 href: used to specify the URL for elements like <a> and <link>
 alt: used to provide alternative text for elements like <img>
 width and height: used to specify the size of elements like <img>
 style: used to apply inline styles to an HTML element

These are just a few examples of the many attributes available in HTML.
Attributes can vary depending on the type of element and the purpose they
serve.

Q5 : Explain about anchor tag and target attribute?

The <a> tag, also known as the anchor tag, is used to create hyperlinks in
HTML. The <a> tag has a href attribute that specifies the URL of the page or
resource to link to.
The target attribute is used in conjunction with the <a> tag and provides
additional information about how the linked page should be displayed. The
target attribute has several possible values, including:

 _self: The linked page will replace the current page and will be
displayed in the same tab or window.
 _blank: The linked page will open in a new tab or window.
 _parent: The linked page will replace the parent frame of the current
page.
 _top: The linked page will replace the entire page, breaking out of any
frames.

For example:
<a href="[Link] target="_blank">Visit
[Link]</a>

In this example, clicking the link will open the [Link]


website in a new tab or window.

Q6 : Explain Various Positions in CSS?

In CSS, there are several positioning values that determine how an HTML
element is positioned within the document. They are:

 static: This is the default value and the element is positioned according
to the normal flow of the document.

 relative: The element is positioned relative to its normal position, but it


can be offset using the top, right, bottom, and left properties.

 absolute: The element is positioned relative to the nearest positioned


ancestor, or the initial containing block if there is no positioned
ancestor. However, if there are no positioned ancestors, the element will
be positioned relative to the body element.
 fixed: The element is positioned relative to the initial containing block,
which is usually the viewport, and it will not move even when the page is
scrolled.

 sticky: The element is positioned according to the normal flow of the


document, but it will be "stuck" to its position when the user scrolls past
it, until it reaches the edge of its parent container.

It's important to note that the position property only determines the type of
positioning, while the top, right, bottom, and left properties are used to offset
the element from its position. Additionally, the z-index property is used to
control the stack order of elements and can be used to overlap elements with
different positions.

Q7 : Explain about Doctype in HTML?

The DOCTYPE declaration in HTML is used to specify the type of document


being used and the version of HTML that the document conforms to. The
DOCTYPE declaration must be the first thing in an HTML document, before
any HTML or head elements.

The DOCTYPE declaration is important because it helps the browser


determine how to render the HTML document. The different types of
DOCTYPEs can vary in syntax and content, and some older versions of HTML
may not be supported by newer browsers.

Here are some common DOCTYPE declarations:

1. HTML5: The latest version of HTML, which is simple and easy to use,
uses the following DOCTYPE declaration:

<!DOCTYPE html>

2. HTML 4.01 Strict: A strict version of HTML 4.01 that only allows the
use of elements and attributes that are considered to be standard and that do
not include presentational or deprecated elements.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"[Link]

3. HTML 4.01 Transitional: A version of HTML 4.01 that includes


elements and attributes that have been deprecated in HTML 4.01 Strict, as
well as some elements used for presentational purposes.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "[Link]

It's important to choose the right DOCTYPE for your HTML document to
ensure that it is rendered correctly by different browsers.

Q8 : Explain about CSS Animations?

CSS animations allow you to create animations and transitions that bring
elements to life on a web page. You can use CSS animations to change the
appearance of an element over time, such as moving, rotating, scaling, or
fading in or out.

Here's an overview of how CSS animations work:

 Define the animation: You need to define the animation by creating


keyframes that specify the styles for different points in the animation.
You use the @keyframes rule to define the keyframes, and you give the
keyframes a name that you will reference in your CSS.

 Apply the animation: You apply the animation to an element using the
animation property in your CSS. The animation property takes several
values that control the duration, iteration count, direction, and timing of
the animation.

 Start the animation: When the animation is applied to an element, it


will start automatically when the page loads. You can also use
JavaScript to start and stop the animation.

Here's an example of a simple CSS animation that changes the opacity of an


element over time:
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}

.element {
animation: fadeIn 2s;
}

In this example, the @keyframes rule defines the keyframes for the animation,
with the from keyframe setting the opacity to 0, and the to keyframe setting
the opacity to 1. The .element class applies the animation to an element, with
the animation property set to fadeIn 2s, which means the animation will last
for 2 seconds.

Q9 : Explain about Responsive Web Design?

Responsive web design is a design approach that makes a website layout


adaptable to different screen sizes and devices, such as desktop computers,
laptops, tablets, and smartphones. The goal of responsive design is to create a
seamless user experience across all devices by delivering a layout that is
optimized for the user's device and screen size.

Here are some of the key elements of responsive web design:

1. Fluid grid: A responsive design uses a fluid grid system that scales the
layout to fit the screen size. The grid system uses relative units like
percentages to specify the width of elements, so the layout adjusts based
on the screen size.

2. Media queries: Media queries are used to apply different CSS styles
based on the screen size and device. With media queries, the design can
change dynamically based on the screen size, orientation, and resolution,
allowing the website to respond to different devices.

3. Flexible images and videos: Images and videos need to be flexible too, so
they don't get cut off or become too large for smaller screens. To make images
and videos responsive, you can use CSS to specify the maximum and
minimum widths for elements and set their height to auto.
4. Text and font sizes: Text and font sizes also need to be adjustable for
different devices. You can use relative units, such as ems or rems, to specify
font sizes, so they scale along with the layout.

Responsive web design is important because it helps to provide a consistent


and optimized user experience across all devices, improving the user's
engagement and satisfaction with your website. Additionally, a responsive
design helps to improve the website's search engine optimization, as search
engines prefer websites that provide a good user experience on all devices.

Q10 : Difference between grid and flex?

CSS Grid and CSS Flexbox are two different layout methods for organizing
elements on a web page. While both can be used to create responsive and
flexible designs, they have some key differences:

Purpose: CSS Grid is best suited for creating two-dimensional layouts with
rows and columns, while Flexbox is best suited for one-dimensional layouts,
either in a row or a column.

Direction: In Grid, items are placed in a two-dimensional grid with rows and
columns, and can span multiple rows and columns. In Flexbox, items are
placed in a one-dimensional row or column, and can wrap to the next line if
needed.

Alignment: Flexbox provides simple and flexible alignment options for items
along the main axis (row or column) and the cross axis. Grid provides a more
powerful alignment system, with options for aligning items both within rows
and columns, as well as between them.

Order: Flexbox allows you to easily change the order of items in the layout,
while in Grid, the order of items is determined by their position in the source
HTML code.

In general, both Grid and Flexbox can be used together in a single layout to
create more complex designs. The choice between Grid and Flexbox often
depends on the specific requirements of the layout and the type of content
being displayed.
Q11 : In how many ways you can style a HTML page?

There are several ways to style an HTML page:

Inline styling: Inline styles can be added to individual HTML elements using
the style attribute. This method is useful for styling specific elements on a
page, but can quickly become difficult to manage as the number of styles
grows.

Internal stylesheet: An internal stylesheet is added to the <head> of an HTML


document using the <style> tag. Styles defined in an internal stylesheet apply
to all elements on the page.

External stylesheet: An external stylesheet is a separate file that contains all of


the styles for a website, linked to the HTML document using the <link> tag in
the <head> of the document. This method is preferred for large websites, as it
allows for easier maintenance and management of styles.

CSS Frameworks: CSS frameworks are pre-prepared libraries that are meant
to allow for easier, more standards-compliant styling of web pages using CSS.
Some popular CSS frameworks include Bootstrap, Foundation, and
Materialize.

CSS Preprocessors: CSS preprocessors, such as Sass and Less, allow you to
write styles using a more advanced syntax, and then compile them into
standard CSS. This method provides additional functionality and makes it
easier to manage and maintain large stylesheets.

JavaScript-based styling: JavaScript can also be used to dynamically style


elements on a page, either by manipulating styles directly or by adding and
removing classes with JavaScript. This method is typically used in
combination with other styling methods, such as CSS.

Q12 : What is the difference between Display:none and visibility:hidden?

display: none and visibility: hidden are two CSS properties used to hide an
element from being displayed on a web page. However, they have some key
differences:

 Layout Impact: display: none removes the element completely from the
layout, so it takes up no space and does not affect the layout of the other
elements on the page. visibility: hidden keeps the element in the layout
and takes up the same amount of space as it would if it were visible, but
makes it invisible.
 Accessibility: When an element has display: none, it is not accessible to
screen readers and other assistive technologies. When an element has
visibility: hidden, it is still accessible to assistive technologies, but
simply not visible to the user.
 Animation: display: none cannot be animated, as it removes the element
from the layout. visibility: hidden can be animated, as it keeps the
element in the layout, but simply changes its visibility.

In general, if you want to completely remove an element from the layout and
don't need to worry about accessibility or animation, use display: none. If you
need to hide an element but keep it in the layout, use visibility: hidden.

Q13 : How to handle events in HTML?

Events in HTML can be handled using JavaScript. To handle an event, you


need to:

1. Identify the element that you want to bind the event to. You can do this
using its id or class attribute.
2. Specify the event you want to bind to. For example, a button click, a
form submit, or an element hover.
3. Write a JavaScript function to handle the event. This function will be
executed when the event occurs.

Here's an example of how to handle a button click event:

HTML:

<button id="myButton">Click Me</button>

JavaScript:

[Link]("myButton").addEventListener("click", function()
{
alert("Button was clicked!");
});
In this example, we first use [Link] to select the button
element with id="myButton". Then, we use addEventListener to bind a click
event to the button, and specify the function that should be executed when the
event occurs.

Q14 : Difference between class and id selector?

In CSS, class selectors and ID selectors are used to select elements and apply
styles to them. The main differences between the two are:

 Selector Type: Class selectors start with a . and select elements based on
their class attribute. ID selectors start with a # and select elements
based on their id attribute.

 Multiple Elements: A class selector can be used to select multiple


elements on a page. An ID selector should only be used to select a single,
unique element on a page.

 Specificity: ID selectors have a higher specificity than class selectors.


This means that if there is a conflict between styles, the styles defined in
an ID selector will take precedence over the styles defined in a class
selector.

 Reuse: Class selectors are reusable, so you can apply the same styles to
multiple elements on a page. ID selectors are meant to be unique, so you
should only use an ID selector to apply styles to a single, specific
element.

Here's an example of how to use class and ID selectors:

HTML:

<p class="blue-text">This is blue text.</p>


<p class="blue-text">This is also blue text.</p>
<p id="red-text">This is red text.</p>

CSS:
.blue-text {
color: blue;
}

#red-text {
color: red;
}
In this example, the .blue-text selector is used to select multiple elements with
the class="blue-text" attribute and apply the color blue to their text. The #red-
text selector is used to select the unique element with the id="red-text"
attribute and apply the color red to its text.

Q15 : How can I change the color of the last anchor element only, where the
element may be dynamically added?

You can change the color of the last anchor element by using JavaScript and
accessing it through the DOM (Document Object Model). Here's an example of
how you could do this:

<script>
[Link]("DOMContentLoaded", function() {
let anchorElements = [Link]("a");
let lastAnchor = anchorElements[[Link] - 1];
[Link] = "red";
});
</script>

In this example, the DOMContentLoaded event is used to wait for the DOM to
be fully loaded before executing the script. Then, getElementsByTagName is
used to get an array of all the a elements on the page. Finally, lastAnchor is
assigned the value of the last element in the anchorElements array, and its
color property is set to red.

This way, regardless of how many anchor elements are on the page or when
they are added, the script will always find the last one and change its color to
red.

Q16 : Difference between inline and block level components?

In HTML, there are two main types of elements: inline elements and block-
level elements.
Inline elements: Inline elements are elements that are placed inline with the
text, and only take up as much width as necessary to display their content.
Examples of inline elements include the a and span tags.

Block-level elements: Block-level elements create a rectangular block that


takes up the full width of their parent container, and create a new line before
and after the element. Examples of block-level elements include the div, p, and
h1 tags.

Here's an example to illustrate the difference between inline and block-level


elements:

HTML:

<p>This is a <span>span</span> element inside a <strong>block-


level</strong> element.</p>

CSS:

p{
background-color: lightgray;
padding: 10px;
}

span {
background-color: yellow;
display: inline;
}

strong {
background-color: lightblue;
display: block;
}

In this example, the p tag is a block-level element, so it creates a rectangular


block with a gray background and padding. The span tag is an inline element,
so it only takes up as much width as necessary to display its content, and has a
yellow background. The strong tag is also a block-level element, so it creates a
new line before and after itself and takes up the full width of its parent
container, with a light blue background.

Q17 : What are tags and elements in HTML?


In HTML, a tag is a keyword surrounded by angle brackets < and > that
specifies a specific type of element. An element is the combination of a start
tag, content, and an end tag that defines a specific type of content on a web
page.

For example, the following code creates a paragraph element:

<p>This is a paragraph of text.</p>

Here, <p> is the start tag, This is a paragraph of text. is the content, and </p>
is the end tag. The combination of the start tag, content, and end tag define a
specific type of content on the web page.

HTML includes many different tags, each with its own specific meaning and
function, such as headings (<h1>, <h2>, etc.), paragraphs (<p>), lists (<ul>,
<ol>, etc.), images (<img>), links (<a>), and more.

It's important to understand the difference between tags and elements in


HTML in order to effectively create and structure content on a web page.

Q18 : How can the text "Mobile no. - 1234567890" be displayed on a website
using HTML and provide the ability to make a call to the number when clicked
without using JavaScript?

To display the text "Mobile no. - 1234567890" and provide the ability to make
a call to the number when clicked without using JavaScript, you can use an
HTML a tag with the tel: protocol. The code would look like this:

<a href="[Link] no. - 1234567890</a>

When the link is clicked, it will initiate a call to the specified number. The tel:
protocol is supported by most modern browsers and mobile devices, so this
should work on both desktop and mobile devices.

Q19 : What is the difference between absolute and relative?

In CSS, "absolute" and "relative" are two different positioning types that
determine the placement of an element in relation to its parent container and
the other elements on the page.
 Absolute positioning: An element with absolute positioning is
positioned relative to the nearest positioned ancestor (instead of
positioned relative to the viewport, like fixed), but it can be moved
anywhere on the page without affecting other elements. If there is no
positioned ancestor, it defaults to being positioned relative to the initial
containing block (usually the body element). The top, right, bottom, and
left properties are used to determine the element's position.
 Relative positioning: An element with relative positioning is positioned
relative to its normal position, and it only moves if the top, right,
bottom, or left properties are set. The other elements on the page are
not affected by this change in position.

In general, absolute positioning is used to create unique, precise layouts while


relative positioning is used to adjust an element's position relative to its
normal position, without affecting the other elements on the page.

Q20 : How to link css with html?

There are three ways to link a CSS stylesheet with an HTML document:

1. External stylesheet: The most common method is to use an external


stylesheet, which is a separate file with the extension .css that contains
all the styles for a webpage. To link an external stylesheet with an HTML
document, you would use the link element in the head section of the
HTML document, like this:

<head>
<link rel="stylesheet" type="text/css" href="path/to/[Link]">
</head>

2. Internal stylesheet: An internal stylesheet is a stylesheet that is defined


within the HTML document itself, using the style element in the head section.
This method is used when you only want to style a single page and don't need
to reuse the styles on multiple pages. The style element would look like this:

<head>
<style>
/* styles go here */
</style>
</head>

3. Inline styles: The CSS can also be applied directly to individual HTML
elements using the style attribute. This method is used when you want to apply
styles to only a specific element and override any styles from the external or
internal stylesheet.

<p style="color: blue;">This is a blue paragraph.</p>


HTML & CSS - FAQ SET 2
_______________________________________________

Q1 : Difference between html and xhtml?

HTML (HyperText Markup Language) and XHTML (Extensible HyperText


Markup Language) are both markup languages used for creating web pages.
They share many similarities but there are some key differences between the
two.

Syntax: XHTML has a stricter and more rigorous syntax compared to HTML.
In XHTML, all elements must be properly nested and closed, and all attributes
must have values.

Document Type Definition (DTD): XHTML uses a strict Document Type


Definition (DTD) that requires the document to be well-formed and adhere to
XML syntax rules. HTML, on the other hand, has looser syntax rules and uses
a loose or transitional DTD.

Case sensitivity: XHTML is case sensitive, while HTML is not. In XHTML, all
elements and attributes must be in lowercase.

Deprecated elements: HTML allows the use of deprecated elements, while


XHTML does not. In XHTML, only those elements that are part of the current
version of HTML are allowed.

Mobile devices compatibility: XHTML is more suitable for use on mobile


devices than HTML, as it requires a well-formed document that can be
processed by small devices with limited processing power.

Overall, XHTML is considered a more modern and forward-looking approach


to web development compared to HTML, as it adheres to XML syntax and
provides a more structured and consistent way of coding web pages. However,
HTML remains the most widely used markup language on the web and has a
large number of resources and tools available for its use.

Q2 : Explain the different types of selectors in CSS?


CSS (Cascading Style Sheets) selectors are used to select and style HTML
elements on a web page. There are several different types of selectors in CSS,
including:

Element Selector: This selector targets specific HTML elements and applies
styles to them. For example, the following code will make all <p> elements
red:

p{
color: red;
}

Class Selector: This selector targets elements with a specific class attribute and
applies styles to those elements. Class selectors start with a period (.). For
example, the following code will make all elements with a class of "highlight"
bold:

.highlight {
font-weight: bold;
}

ID Selector: This selector targets a unique element with a specific id attribute


and applies styles to that element. ID selectors start with a hash symbol (#).
For example, the following code will make the element with an id of "header"
have a background color of green:

#header {
background-color: green;
}

Universal Selector: This selector targets all elements on a page and applies
styles to them. The universal selector is represented by an asterisk (*). For
example, the following code will set the margin and padding of all elements to
0:

*{
margin: 0;
padding: 0;
}

Attribute Selector: This selector targets elements with a specific attribute and
applies styles to those elements. For example, the following code will make all
links with the target="_blank" attribute have a color of blue:

a[target="_blank"] {
color: blue;
}

Pseudo-class Selector: This selector targets elements in a specific state and


applies styles to them. For example, the following code will make all links with
a hover state have a background color of yellow:

a:hover {
background-color: yellow;
}
Adjacent Sibling Selector: This selector targets elements that are siblings of
another element and applies styles to them. For example, the following code
will make the second <p> element red:

p+p{
color: red;
}

Child Selector: This selector targets elements that are children of another
element and applies styles to them. For example, the following code will make
the first <li> element blue:

ul > li:first-child {
color: blue;
}

These are some of the most commonly used selectors in CSS. Understanding
these selectors is essential for writing efficient and effective CSS code.

Q3 : How can you center a div both horizontally and vertically?

To center a div both horizontally and vertically, you can use a combination of
CSS techniques. Here's an example:

HTML:

<div class="outer-container">
<div class="inner-container">
Content goes here
</div>
</div>

CSS:

.outer-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.inner-container {
width: 50%;
height: 50%;
background-color: lightgray;
text-align: center;
}
In this example, the outer container is set to display: flex and align-items:
center to vertically center its contents. The justify-content: center property is
used to horizontally center the inner container. The height of the outer
container is set to 100vh (100% of the viewport height) to ensure that it covers
the full height of the screen. The inner container is given a width and height of
50% to make it smaller and is centered within the outer container using text-
align: center.

You can adjust the width, height, and other properties to meet your specific
needs.

Q4 : Explain about different CSS units?


CSS provides several units to specify length values such as width, height,
padding, margins, etc. These units include:

 Pixels (px): Pixels are absolute units that are fixed in size and not
relative to the size of the viewport or any other element. They are
commonly used for specifying the size of font, border, and padding.

 Percentage (%) : Percentages are relative units that are calculated based
on the size of the parent element. For example, if you set the width of an
element to 50%, it will take up 50% of the width of its parent element.

 Em (em): An em is a relative unit that is based on the font-size of the


element. It is commonly used for specifying the size of font and padding.
The default value of 1em is equal to the font-size of the element.

 Rem (rem): The rem unit is similar to the em unit, but it is based on the
root font-size of the document. It is useful for creating scalable and
responsive designs as it ensures that all elements are proportionally
sized in relation to the root font-size.

 Viewport units (vw, vh, vmin, vmax): These units are based on the size
of the viewport (the visible area of a web page) and are useful for
creating responsive designs. vw represents 1% of the width of the
viewport, vh represents 1% of the height of the viewport, vmin
represents the smaller value between vw and vh, and vmax represents
the larger value between vw and vh.

 Points (pt): Points are absolute units that are commonly used for
specifying font sizes. A point is equivalent to 1/72 of an inch.
These are the most commonly used CSS units. It is important to understand
the difference between these units and choose the right unit for your specific
needs, based on whether you want the length value to be absolute or relative,
and how you want the length to scale in different viewport sizes.

Q5 : What is the difference between absolute and relative?

In CSS, absolute and relative are positioning values that determine how an
element is positioned within the document flow.

Absolute positioning takes an element out of the document flow and positions
it relative to its nearest positioned ancestor, or if there is no positioned
ancestor, it is positioned relative to the initial containing block (usually the
body element). The element will not affect the layout of other elements and
will remain in the same position even if the page is scrolled.

Relative positioning keeps an element within the document flow and adjusts
its position relative to its normal position. For example, if you set the top
property to 20px, the element will be moved 20px down from its normal
position. Unlike absolute positioning, relative positioning does not take an
element out of the document flow, so other elements will still be affected by
the element's position and size.

In conclusion, the main difference between absolute and relative positioning is


that absolute positioning takes an element out of the document flow, while
relative positioning keeps an element within the document flow but adjusts its
position.

Q6 : What are HTML semantic elements?

HTML semantic elements are HTML elements that have a specific meaning to
both the browser and the developer. These elements help to improve the
accessibility and structure of a web page.

Some of the most commonly used HTML semantic elements are:

<header>: Defines a container for the header content, such as the logo,
navigation menu, and other site-wide elements.

<nav>: Defines a container for navigation links.

<main>: Defines the main content of a document, excluding header, footer,


and navigation.

<article>: Defines a self-contained content piece, such as a blog post, a news


article, or a forum post.
<section>: Defines a content section that has a specific theme and is often
used to group related content together.

<aside>: Defines content that is tangentially related to the main content and is
typically displayed as a sidebar.

<footer>: Defines the footer content, such as the copyright information, links
to legal documents, and site-wide elements.

<figure>: Defines a content piece that is self-contained and is typically


accompanied by a caption.

<figcaption>: Defines a caption for a <figure> element.

Using semantic elements helps to improve the accessibility and search engine
optimization of a web page, making it easier for users and search engines to
understand the structure and content of the page.

Q7 : What are the different properties of flexbox?

Flexbox is a CSS layout model that provides an efficient way to align and
distribute space among elements within a container. It allows for easy control
of elements along a main axis and cross axis. The following are some of the
most commonly used properties of flexbox:

display: Specifies the type of box used for an element. The value should be set
to flex to enable flexbox behavior for an element.

flex-direction: Specifies the main axis of the flex container. The default value is
row, which aligns elements horizontally from left to right. Other values include
row-reverse, column, and column-reverse.

flex-wrap: Specifies how elements should wrap within the container. The
default value is nowrap, which means elements will not wrap to the next line.
The wrap value allows elements to wrap to the next line, while wrap-reverse
wraps elements in the opposite direction.

justify-content: Specifies how to align elements along the main axis. The
default value is flex-start, which aligns elements to the start of the main axis.
Other values include flex-end, center, space-between, and space-around.

align-items: Specifies how to align elements along the cross axis. The default
value is stretch, which stretches elements to fill the container. Other values
include flex-start, flex-end, center, and baseline.

align-content: Specifies how to align elements along the cross axis after
wrapping. The default value is stretch, which stretches elements to fill the
container. Other values include flex-start, flex-end, center, space-between, and
space-around.

Flex-grow: Specifies how much an element should grow relative to the other
elements in the container. The default value is 0, which means the element
will not grow. A value of 1 means the element will grow to fill any remaining
space in the container.

Flex-shrink: Specifies how much an element should shrink relative to the


other elements in the container. The default value is 1, which means the
element will shrink if necessary to fit within the container.

Flex-basis: Specifies the starting size of an element along the main axis before
any growing or shrinking occurs. The default value is auto, which means the
element will have its natural size.

These are some of the most commonly used properties of flexbox. By using
these properties, you can create complex and flexible layouts that adapt to
different screen sizes and devices.

Q8 : How can we access DOM?

The Document Object Model (DOM) is a programming interface for HTML


and XML documents. You can access the DOM to manipulate and modify the
content and structure of a web page. There are several ways to access the DOM
in JavaScript:

Using the document object: The document object is the top-level object in the
DOM and represents the entire document. You can use it to access the
elements, attributes, and content of a web page. For example, you can use the
[Link]() method to access an element by its ID, or the
[Link]() method to access an element based on a CSS
selector.

Using the window object: The window object is the top-level object in the
browser and represents the entire window or tab. You can use it to access the
DOM and the properties of the window. For example, you can use the
[Link] property to access the height of the window or the
[Link] property to access the document object.

Using the element object: Each element in the DOM has its own element
object, which you can use to access its properties, attributes, and content. For
example, you can use the [Link] property to access the inline style of an
element, or the [Link] property to access the classes of an element.

Using the node object: The node object is a general-purpose object that
represents an element, attribute, text node, or comment in the DOM. You can
use it to access the properties and methods common to all nodes in the DOM.
For example, you can use the [Link] property to access the name of a
node, or the [Link]() method to add a new node as a child of an
existing node.

These are the main ways to access the DOM in JavaScript. By using these
methods, you can interact with the content and structure of a web page and
create dynamic and interactive experiences for users.

Q9 : What are features of HTML5?

HTML5 is the latest version of the HTML (Hypertext Markup Language)


standard, and it introduces a number of new features and capabilities to the
web development world. Some of the key features of HTML5 include:

Semantic Elements: HTML5 introduces a number of new semantic elements,


such as header, footer, nav, section, article, aside, and figure, which make it
easier to structure the content of a web page. These elements provide
additional meaning to the content and make it easier for search engines and
other technologies to understand the content of a web page.

Video and Audio: HTML5 includes new elements for embedding video and
audio content directly in a web page, without the need for plugins like Flash.
This makes it easier to include multimedia content in a web page and provides
a more consistent experience across different devices and platforms.

Canvas: HTML5 introduces a new canvas element, which allows for dynamic
and interactive graphics on the web. The canvas element provides a way for
developers to programmatically draw shapes, images, and animations in a web
page.

Local Storage: HTML5 introduces a new way to store data on the client-side,
called local storage. This allows web applications to store data on the user's
device and access it later, even when the user is offline.

Geolocation: HTML5 introduces new APIs for accessing the user's location
information, making it possible to create location-aware web applications.

Web Workers: HTML5 introduces a new way to run background scripts in a


web page, called web workers. This allows for heavy computation to be
performed in the background, without affecting the performance of the main
page.

Drag and Drop: HTML5 introduces new APIs for implementing drag-and-drop
functionality in a web page, making it easier to create interactive and user-
friendly interfaces.
These are just a few of the many features of HTML5. Overall, HTML5 provides
a more rich and powerful platform for web development, making it easier to
create dynamic and interactive experiences for users.

Q10 : Explain about CSS Box Model?

The CSS Box Model is a concept that describes how the dimensions of an
HTML element are calculated in CSS. It determines the size and spacing of an
element, and includes the following components:

 Content: This is the actual content of the element, such as text or an


image.

 Padding: This is the space between the content and the border of the
element. The padding can be customized using the CSS padding
property.

 Border: This is a line that surrounds the content and padding of an


element. The border can be customized using the CSS border property.

 Margin: This is the space outside of the border, between the border of
an element and the surrounding elements. The margin can be
customized using the CSS margin property.

The CSS Box Model is used to calculate the total width and height of an
element, which includes the width and height of the content, plus the padding,
border, and margin. By default, the CSS Box Model adds the padding and
border to the width and height of an element, but this can be changed using
the box-sizing property.

In conclusion, the CSS Box Model is a fundamental concept in CSS that


determines the size and spacing of an element, and provides a way to control
the dimensions of an element in a web page. By understanding and using the
CSS Box Model, you can create more sophisticated and engaging web pages
with CSS.

Q11 : What are formatting tags?

Formatting tags in HTML are elements that are used to define the appearance
and layout of text and other content on a web page. These tags allow you to
specify how text should be displayed, including font size, font style, text color,
and more. Some common formatting tags in HTML include:
 <p>: The paragraph tag, used to define a paragraph of text.

 <strong>: The strong tag, used to make text bold.

 <em>: The emphasis tag, used to italicize text.


 <u>: The underline tag, used to underline text.

 <sup>: The superscript tag, used to create superscript text.

 <sub>: The subscript tag, used to create subscript text.

 <br>: The line break tag, used to insert a line break in the text.

 <hr>: The horizontal rule tag, used to insert a horizontal rule on the
page.

 <font>: The font tag, used to specify font size, color, and face.

In addition to these tags, there are many other formatting tags available in
HTML, and new tags are constantly being added with each new version of
HTML. However, it's important to note that these formatting tags are being
phased out in favor of CSS, which provides more control and versatility in
styling text and other content on a web page.

Q12 : What are pseudo-classes?

Pseudo-classes in CSS are special keywords that are added to selectors to


select elements based on their state or attributes. They allow you to style
elements based on a specific state, such as when a user hovers over a link or
when an input field is focused. Some common pseudo-classes include:

:hover: Matches elements when the user hovers over them.

:active: Matches elements when they are being activated, such as a button
being pressed.
:focus: Matches elements when they have focus, such as an input field being
selected.

:visited: Matches links that have already been visited by the user.

:first-child: Matches the first child element of a parent element.

:nth-child(n): Matches the nth child element of a parent element.

:last-child: Matches the last child element of a parent element.

Pseudo-classes provide a powerful way to select and style elements based on


their state, and they can be used in combination with other selectors to create
complex, dynamic styles. For example, you can use the :hover pseudo-class to
change the background color of a link when the user hovers over it, or the
:focus pseudo-class to change the outline of an input field when it is selected.

In conclusion, pseudo-classes are an important aspect of CSS that allow you to


select elements based on their state and attributes, providing a way to create
dynamic, interactive styles for your web pages.

Q13 : what are 4 values in margin and padding?

In CSS, margins and padding both allow you to control the space around
elements on a web page. The difference between the two is that margins
control the space outside of an element, while padding controls the space
inside of an element.

Both margins and padding can be specified using four values, which represent
the top, right, bottom, and left sides of an element. These values can be
specified in the following order:

margin: top right bottom left;


padding: top right bottom left;

Each value can be specified using a length unit, such as pixels or ems, or a
percentage. If you specify only one value, it will be applied to all four sides of
the element. If you specify two values, the first value will be applied to the top
and bottom, and the second value will be applied to the left and right. If you
specify three values, the first value will be applied to the top, the second value
will be applied to the left and right, and the third value will be applied to the
bottom.

For example, the following CSS would apply a 20-pixel margin to the top and
bottom of an element and a 10-pixel margin to the left and right:
margin: 20px 10px;

You can also specify individual values for each side using the following syntax:
margin-top: 20px;
margin-right: 10px;
margin-bottom: 20px;
margin-left: 10px;

And the same syntax can be used for padding:

padding-top: 20px;
padding-right: 10px;
padding-bottom: 20px;
padding-left: 10px;

Q14 : Make 2 div inline having the same gap in between?

To make two divs inline with the same gap in between, you can use the
display: inline-block property and set a width for each div. Then, you can use
the margin property to add a gap in between.

Here's an example:

div {
display: inline-block;
width: 40%;
margin: 0 10% 0 10%;
background-color: lightgray;
}

In this example, each div will have a width of 40% of its parent container and a
10% margin on both the left and right sides. The display: inline-block property
allows the divs to appear on the same line, as if they were text.

You can also use the text-align property to center the divs within their parent
container, if desired:

.container {
text-align: center;
}

Q15 : What are private and global attributes in HTML?

In HTML, there are no specific terms like "private" and "global" attributes.
However, you can understand the concept of global and private attributes in
terms of the scope of an attribute.

A global attribute is one that can be used on any HTML element, regardless of
the type of element it is. For example, the class attribute is a global attribute
that can be used on any HTML element to specify a class name.
A private attribute, on the other hand, is specific to a particular element type
and cannot be used on other element types. For example, the cols attribute is a
private attribute that can only be used on the textarea element to specify the
number of columns in the text area.

In general, it's best to use global attributes whenever possible, as they provide
more flexibility and can be used on a wider range of elements. However,
private attributes may be necessary in some cases to provide more specific
control over an element.

Q16 : How is the nth-child() different from nth of type selectors?

The :nth-child() and :nth-of-type() selectors in CSS are used to select elements
based on their position within a parent element. However, there is an
important difference between these two selectors:

:nth-child() selects elements based on their position within all of the children
of a parent element, regardless of the type of element.

:nth-of-type() selects elements based on their position within a group of


similar elements, considering only elements of the same type.

For example, consider the following HTML:

<ul>
<li>Item 1</li>
<li>Item 2</li>
<p>Item 3</p>
<li>Item 4</li>
</ul>

If you want to select the third li element using the :nth-child() selector, you
would write:

li:nth-child(3) {
background-color: lightgray;
}

In this case, the third child element selected would be the p element, as it is
the third child of the parent ul element.

If you want to select the third li element using the :nth-of-type() selector, you
would write:

li:nth-of-type(3) {
background-color: lightgray;
}
In this case, the third li element selected would be Item 4, as it is the third li
element within the group of li elements.

So in short, :nth-child() selects an element based on its position among all


elements, while :nth-of-type() selects an element based on its position among
elements of the same type.

Q16 : What is a z-index, how does it function?

The z-index property in CSS is used to specify the stacking order of elements
on a web page. When elements overlap, the element with a higher z-index
value will appear in front of elements with a lower z-index value.

The z-index property only affects the stacking order of elements that have a
position value of absolute, relative, or fixed. For example:

.element1 {
position: absolute;
z-index: 1;
}

.element2 {
position: absolute;
z-index: 2;
}

In this example, .element2 will appear in front of .element1 because it has a


higher z-index value.

It's important to note that the z-index property only applies within the same
parent element. For example, if .element2 is a child of .element1, it will appear
in front of .element1 even if its z-index value is lower.

The z-index property can be a positive or negative integer value, with higher
values indicating that an element should appear in front of elements with
lower values. The default z-index value is 0, so elements with a specified z-
index value will appear in front of elements with the default value.

Q17 : Can you construct a popup structure without relying on any external
libraries, such as Bootstrap?

Yes, it's possible to create a popup structure in HTML, CSS, and JavaScript
without using any external libraries like Bootstrap. Here's an example of how
you can create a basic popup structure:

HTML:
<button id="myBtn">Open Popup</button>

<div id="myModal" class="modal">


<div class="modal-content">
<span class="close">&times;</span>
<p>This is a Popup</p>
</div>
</div>

CSS:

.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}

.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}

JavaScript:
// Get the modal
var modal = [Link]("myModal");

// Get the button that opens the modal


var btn = [Link]("myBtn");

// Get the <span> element that closes the modal


var span = [Link]("close")[0];

// When the user clicks the button, open the modal


[Link] = function() {
[Link] = "block";
}

// When the user clicks on <span> (x), close the modal


[Link] = function() {
[Link] = "none";
}

// When the user clicks anywhere outside of the modal, close it


[Link] = function(event) {
if ([Link] == modal) {
[Link] = "none";
}
}

This is a basic example of how you can create a popup structure in HTML,
CSS, and JavaScript without relying on any external libraries. You can modify
and expand the functionality to meet your needs.

Q18 : Why do we use float property in css?

The float property in CSS is used to position an element to the left or right of
its container, allowing other elements to wrap around it. This is commonly
used to create a layout for elements such as images, captions, and headers,
where text should flow around the floated element.

For example, consider the following HTML and CSS code:

<div style="width: 500px;">


<img src="[Link]" style="float: left; width: 200px;">
<p>This is some text that will flow around the floated image on the left.</p>
</div>

In this example, the image is floated to the left, and the text will wrap around
it, as if the image is being taken out of the normal flow of the document and
placed to the left.
It's important to note that when using the float property, the container
element may not automatically adjust its height to accommodate the floated
elements, so you may need to use clearfix or other methods to ensure that the
container retains the correct height.

Q19 : How to create a nested web-page in HTML?

To create a nested web-page in HTML, you'll need to use an iframe. An iframe


(inline frame) is an HTML element that allows you to embed one HTML
document inside another.

Here's an example of how to create an iframe in HTML:

<iframe src="[Link]" width="600" height="400"></iframe>

In this example, the src attribute specifies the URL of the nested web-page,
and the width and height attributes set the dimensions of the iframe.

You can also style the iframe using CSS, for example to add borders,
background color, or to set its position on the page. Here's an example of how
to style an iframe:

iframe {
border: 1px solid black;
background-color: white;
position: absolute;
top: 50px;
left: 50px;
}

In this example, the iframe has a black border, a white background color, and
is positioned 50 pixels from the top and left of the containing element.

Q20 : How to create a hyperlink in HTML?

A hyperlink, also known as a link, is used to connect one web page to another.
To create a hyperlink in HTML, you can use the <a> (anchor) element.

Here's an example of how to create a hyperlink in HTML:

<a href="[Link]

In this example, the <a> element has a href attribute, which specifies the URL
of the page that the link should navigate to when clicked. The text between the
opening and closing <a> tags is the text that will be displayed as the link.
You can also create links to other types of resources, such as email addresses,
phone numbers, and files, by using different URL schemes. For example:

<a href="[Link] Us</a>


<a href="[Link] Us</a>
<a href="[Link]">Download PDF</a>

In these examples, the first link opens the user's email client and creates a new
email to info@[Link], the second link opens the user's phone
application and dials the specified number, and the third link downloads the
file "[Link]"
React - FAQ Set 1
____
________________________________________________________

Q1 - What is React? Is React a library or a framework?

React is a JavaScript library for building user interfaces. It is used for building
reusable UI components and managing the state of those components. React allows
developers to build complex user interfaces by breaking them down into smaller,
reusable components. It is not considered a framework because it does not provide a
built-in structure for application development, unlike Angular or [Link]. Instead, it
focuses on the view layer of an application and can be easily integrated with other
libraries or frameworks for complete application development.

Q2 - What is the useState hook?

The useState hook is a built-in hook in React that allows you to add state to
functional components. It is an alternative to using the class component syntax and
[Link] to manage state in a React application. The useState hook takes an initial
state as an argument and returns an array containing the current state and a setter
function for updating the state.

Here is an example of using the useState hook to create a counter component:

import { useState } from 'react';

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

return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
In this example, the useState hook is used to create a count state variable with an
initial value of 0. The hook returns an array containing the current value of count
and a setCount function that can be used to update the value of count. The
component renders a button that, when clicked, increments the value of the count
state variable.

The useState hook is a very powerful tool that allows to manage the state of your
component in a simple and efficient way, it's the most basic hook provided by React,
but you can use other hooks like useEffect, useContext, useReducer.. etc to make
your component more complex and handle more complex state.

Q3 - What are props and state?

In React, props (short for "properties") and state are used to manage the data and
behavior of a component.

props are used to pass data down from a parent component to its child components.
They are considered "read-only" and cannot be modified directly by the child
components. Props are passed to a component as an argument when it is being
rendered, and can be accessed inside the component using the props object.

Here is an example of passing props from a parent component to a child component:

import ChildComponent from './ChildComponent';

function ParentComponent() {
const message = 'Hello World';

return <ChildComponent message={message} />;


}

In this example, the ParentComponent is passing a message prop to the


ChildComponent. The ChildComponent can then access the message prop using the
props object:

function ChildComponent(props) {
return <h1>{[Link]}</h1>;
}

state, on the other hand, is used to manage the internal data and behavior of a
component. It is considered "private" to the component and can only be modified by
the component itself. Unlike props, state can change over time, and when it changes,
the component will re-render to reflect the changes. State is typically used to keep
track of data that can be changed by user interactions or other events.

Here is an example of using state in a component:

import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}

In this example, the component is using the useState hook to create a count state
variable with an initial value of 0. The component then renders a button that, when
clicked, increments the value of the count state variable.

To sum up, props are used to pass data down from parent components, while state is
used to manage the internal data and behavior of a component.

Q4 - how to update states in child component state in parent component

There are a few ways to update the state of a child component from a parent
component in React, depending on the specific use case.

One way is to pass a callback function from the parent component to the child
component as a prop. The child component can then call this function when it needs
to update its state, and the parent component can use this function to update the
child's state.

For example, in the parent component:


function ParentComponent() {
const [childState, setChildState] = useState(0);

const handleChildStateChange = (newState) => {


setChildState(newState);
}

return <ChildComponent state={childState}


onStateChange={handleChildStateChange} />;
}

In this example, the parent component is passing a state prop and a onStateChange
callback function to the ChildComponent.

In the child component:

function ChildComponent(props) {
const handleClick = () => {
[Link]([Link] + 1);
}

return (
<>
<h1>{[Link]}</h1>
<button onClick={handleClick}>Increment</button>
</>
);
}

In this example, the child component is using the handleClick function to call the
onStateChange callback function passed from the parent component, which updates
the child's state.

Another way to update the state in child component is to use the useContext hook,
where the parent component creates a context and the child component consume it.

Another way is to use the useReducer hook, where the parent component holds the
state and the child component dispatches the action to update the state.
It's depend on the complexity of your application, and the structure you like to use in
your application.

Q5 - Explain your understanding of Prop drilling?

Prop drilling, also known as "prop-tunnelling" or "lifting state up," is a technique


used in React to pass data and functions down through multiple levels of
components.

When a component needs to pass data or functions to a child component that is


several levels down in the component tree, it can pass the data or functions through
each intermediate component as props. This process is known as "prop drilling."

Here is an example:

function ParentComponent() {
const data = { name: 'John', age: 30 };

return (
<ChildA>
<ChildB>
<ChildC data={data} />
</ChildB>
</ChildA>
);
}

In this example, the ParentComponent is passing a data prop to the ChildC


component. However, the ChildC component is nested several levels deep inside the
component tree, so the data prop needs to be passed through ChildA and ChildB as
well. This is prop drilling.

The problem with prop drilling is that it can make the component tree more complex
and harder to understand, as well as make components more dependent on each
other. Also, it can make the component tree less flexible and harder to refactor in the
future.
There are several ways to avoid prop drilling such as using the context API and redux
to share data between components at different levels of the component tree. It's also
possible to use the useContext hook, which allows you to share data between
components without having to pass it down through props.
It's important to consider the structure of your component tree and to try to
minimize the amount of prop drilling as much as possible in order to make your
application more maintainable and easier to understand.

Q6 - Explain about Life cycle methods?

In React, a component goes through several stages during its lifetime, from the
moment it is first rendered on the page to the moment it is removed. These stages are
known as the component's "lifecycle." React provides several lifecycle methods that
you can use to add functionality to your components at different points in their
lifecycle.

Here are some of the most commonly used lifecycle methods in React:

 componentDidMount(): This method is called after the component has been


rendered to the DOM for the first time. This is a good place to perform any
setup that requires the DOM, such as fetching data or setting up event
listeners.
 componentDidUpdate(prevProps, prevState): This method is called after the
component's props or state have been updated. This is a good place to perform
any additional updates or side effects that depend on the new props or state.
 componentWillUnmount(): This method is called just before the component is
removed from the DOM. This is a good place to perform any cleanup that
needs to happen, such as removing event listeners or canceling network
requests.
 shouldComponentUpdate(nextProps, nextState): This method is called before
the component is re-rendered after an update. It receives the next props and
state as arguments and should return a boolean value indicating whether the
component should update.
 render(): This method is the most important lifecycle method. It is called
when the component is first rendered, and whenever the component's props
or state change.

It's important to note that these lifecycle methods are only available on class
components and are not available on functional components. However, you can use
hooks like useEffect to handle side effects inside functional component and manage
the component life cycle in functional component.

It's also important to note that some lifecycle methods have been marked as
deprecated and will be removed in future versions of React. It's always a good idea to
check the React documentation and make sure you're using the latest and
recommended way of handling component's lifecycle.

Q7 - what is inside an [Link] file in the public folder of react app?


The [Link] file located in the public folder of a React app is the root file of the
app. It is the file that is served to the browser when the app is loaded. It typically
contains the basic structure of the app's HTML, including the <head> and <body>
tags, as well as the <div> element where the React app will be rendered.

The basic structure of an [Link] file for a React app might look like this:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>My React App</title>

</head>

<body>

<div id="root"></div>

</body>

</html>

The <div id="root"></div> is the place where the React app will be rendered. The
JavaScript files that React application include are usually added to the <head>
element, but the latest versions of create-react-app template include a <script> tag
that loads the JavaScript file at the end of the <body> element, this is to ensure that
the app's JavaScript files are loaded after the HTML has been parsed by the browser.

The [Link] file may also include other elements such as <link> tags for styling
the app, <meta> tags for SEO, and <script> tags for loading additional libraries or
resources.

It's also worth noting that the [Link] file in a React app is not typically modified
directly, because it's generated by the build process of the react application and is
intended to be used as a template. Any customization that needs to be done to the
HTML file should be done through the [Link] file or [Link] file that imports the
[Link] file.

Q8 - what is Redux and its application?


Redux is a JavaScript library that is commonly used in combination with React to
manage the application's state. It provides a way to manage the state of the
application in a centralized location, known as the "store."
The main idea behind Redux is to keep the state of the application in a single,
immutable store. This store can be updated only by dispatching an action, which is
an object that describes a change to the state. The store will then pass the action
through a set of "reducers," which are functions that update the state based on the
action.

Redux provides a few key benefits for managing the state of a React application:

 Centralized state management: With Redux, all the state of the application is
stored in a single location, which makes it easy to understand and manage the
state of the entire application.
 Predictable state updates: Redux uses actions and reducers to update the
state, which makes it easy to understand how the state will change in response
to a specific action.
 Easy debugging: Redux provides a way to record the history of actions and
state changes, which makes it easy to understand how the state of the
application changed over time.
 Easy to test: Because actions and reducers are simple functions, they are easy
to test in isolation.

The most common use case for Redux is when an application needs to manage a
large amount of state, or when the state needs to be shared between multiple
components. It's especially useful in larger and more complex applications as it
provides a way to manage the state in a scalable and predictable manner.

It's worth noting that not all React applications need to use Redux, it depends on the
complexity of the application and the way the state is managed. But, it's a powerful
tool that can help you organize your state in a more predictable way and make it easy
to reason about the state of your application.

Q9 - What is SPA?

A Single-Page Application (SPA) is a type of web application that loads a single


HTML page and dynamically updates the content as the user interacts with the app.
Instead of navigating to different pages, the SPA loads all the necessary code and
resources at once and updates the content in place.

Some common features of SPAs include:

 Dynamic updates to the content without requiring a full page refresh


 Use of JavaScript to handle client-side logic and interact with the server
 Use of a client-side router to handle navigation and update the content in
place
 Use of AJAX to communicate with the server and update the content
dynamically

One of the most popular frameworks and library to build SPA is React, Angular and
[Link], they are all JavaScript libraries that allow developers to build dynamic,
interactive user interfaces. These libraries allow you to break down the UI into
reusable components, manage the state of the application, and handle routing.

SPAs are becoming increasingly popular because they provide a more seamless and
responsive user experience, as well as better performance and offline capabilities.
They are often used for building web-based applications, such as email clients, social
media apps, and e-commerce sites.

It's worth noting that SPA's also have some disadvantages like SEO, as the search
engines have difficulties indexing the dynamic content of SPAs, and also the loading
time for the initial load of the application.

Q10 - A application having home,contact us etc tabs using routes, is it a SPA? Give
your reasoning?

An application with home, contact us, etc. tabs that uses routes to navigate between
different pages can be considered a Single-Page Application (SPA).

The key characteristic of a SPA is that it loads a single HTML page and dynamically
updates the content as the user interacts with the app. In the case of the application
you've described, the user is able to navigate between different pages (home, contact
us, etc.) without a full page refresh, which is a key feature of a SPA.

Additionally, the use of routes to handle navigation is a common feature of SPAs. A


client-side router is often used to handle routing in a SPA. The router listens for
changes to the URL and updates the content in place based on the current route. This
allows the user to have a seamless experience, as the whole page doesn't need to be
reloaded when the user navigates to a different page.

Furthermore, the use of JavaScript to handle client-side logic and interact with the
server is another common feature of SPAs. In this case, the application uses
JavaScript and routes to dynamically update the content and handle navigation,
which is also a common feature of SPAs.

In summary, because the application you've described uses routes to navigate


between different pages without a full page refresh, and uses JavaScript to handle
client-side logic, it can be considered a Single-Page Application (SPA).

Q11 - Why do we use React?

React is a JavaScript library for building user interfaces (UI) that is widely used for
building web applications. There are several reasons why developers choose to use
React:

 Component-based architecture: React allows you to build your UI as a set of


reusable components. This makes the code more maintainable and easier to
understand, and allows for better separation of concerns.
 Virtual DOM: React uses a virtual DOM (Document Object Model) to improve
the performance of updates to the UI. The virtual DOM is a lightweight
representation of the actual DOM, and React uses it to determine the minimal
set of updates that need to be made to the actual DOM. This improves the
performance of the application by reducing the number of updates that need
to be made to the DOM.
 Easy to learn: React has a relatively simple API, and its component-based
architecture makes it easy to understand and work with. This makes it a good
choice for developers who are new to building web applications.
 Large community and ecosystem: React has a large and active community,
which means there are many resources available for learning and
troubleshooting. Additionally, there are many third-party libraries and tools
available for React, which can help speed up development and add additional
functionality to your application.
 Flexible: React can be used with other libraries and frameworks, such as
Redux for state management, React Router for client-side routing, and [Link]
for server-side rendering. This flexibility allows developers to choose the tools
that best fit their needs.
 Popular in industry: React is widely used by many companies and
organizations, such as Facebook, Airbnb, Netflix, Uber, etc. This means that
it's a well-established technology with a proven track record of success, and
that there are many job opportunities available for React developers.

In summary, React is a powerful and flexible tool for building web applications, it has
a component-based architecture, uses a virtual DOM for performance, has a large
community, is easy to learn and widely used in the industry.

Q12 : What is class component in react?

In React, a class component is a way to create a component using a JavaScript class.


A class component is defined as a JavaScript class that extends the [Link]
base class, and has a render() method that returns JSX.

Here's an example of a simple class component in React:

import React, { Component } from 'react';

class MyComponent extends Component {

render() {

return <h1>Hello, World!</h1>;

This class component, MyComponent, is defined as a JavaScript class that extends


the [Link] base class. The render() method returns JSX that will be
rendered in the browser.
Class components have some advantages over functional components, for example,
you can use class components to use the lifecycle methods of react, like
componentDidMount, componentWillUnmount, etc.

Additionally, class components can also hold state, and can use a constructor to
initialize the state, while functional components can't hold state.

It's worth noting that the use of class components has been declining in recent years,
as the introduction of hooks in React allows developers to use state and lifecycle
methods in functional components as well.

It's important to note that you don't have to use class components, you can use
functional components with hooks to achieve the same functionality and it's up to
your preference which one to use.

Q13 - Explain about Virtual DOM?

The virtual DOM (Document Object Model) is a technique used by React to optimize
the performance of updates to the UI. The virtual DOM is a lightweight, in-memory
representation of the actual DOM, and React uses it to determine the minimal set of
updates that need to be made to the actual DOM.

When a component's state changes, React will first create a new virtual DOM tree
representing the updated UI. It will then compare this new tree to the previous
virtual DOM tree, and determine the minimal set of changes required to update the
actual DOM. This process is called "reconciliation."

The virtual DOM has several benefits:

 Performance: By minimizing the number of updates that need to be made to


the actual DOM, the virtual DOM can significantly improve the performance
of an application.
 Decoupling: The virtual DOM is decoupled from the actual DOM, which
means that React can update the UI independently of the browser. This allows
React to work with different types of rendering environments, such as web,
mobile, and server-side.
 Abstraction: The virtual DOM provides an abstraction layer that allows React
to update the UI without requiring developers to directly manipulate the
actual DOM. This makes it easier to write and maintain React components.
 Simplifying updates: By comparing the virtual DOM to the previous virtual
DOM, React can determine the minimal set of changes required to update the
actual DOM. This makes it easier to reason about and debug the updates being
made to the UI.

It's worth noting that the virtual DOM is not unique to React,

Q14 - what is the use of a callback hook?


In React, a callback hook is a hook that is used to pass a callback function from a
parent component to a child component. The child component can then use the
callback function to communicate with the parent component.

The most common use case for a callback hook is when a child component needs to
update the state of a parent component. For example, consider a simple counter
component that increments a count when a button is clicked:

function ParentComponent() {

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

return (

<>

<ChildComponent onClick={() => setCount(count + 1)} />

<p>Count: {count}</p>

</>

);

In this example, the ParentComponent is passing an onClick callback to the


ChildComponent. The ChildComponent can then use this callback to increment the
count when the button is clicked.

Callback hooks are also used when a child component needs to notify the parent
component of an event, such as when a form is submitted, when a button is clicked,
or when a user changes a value.

It's worth noting that callback hooks are not unique to React, this pattern is widely
used in other JavaScript libraries and frameworks as well.

It's also worth noting that callback hooks are used to maintain the unidirectional
flow of data in react, where the data flows from the top-level component to the child
components, and the child component can only update the parent component state
through callback hooks.

Q15 - Why do we use Useeffect? what is use of dependency in useEffect?

useEffect is a hook in React that allows you to synchronize a component with an


external system, such as a browser API or a back-end service. It allows you to run
side effects, such as fetching data or setting up event listeners, in a functional
component.
useEffect takes two arguments: a callback function and an array of dependencies.
The callback function is executed after the component has rendered, and it can
contain any side effects that you want to run. The array of dependencies is a list of
values that the effect depends on.

Here is an example of how to use useEffect to fetch data in a functional component:

function MyComponent() {

const [data, setData] = useState([]);

useEffect(() => {

async function fetchData() {

const response = await fetch('[Link]

const json = await [Link]();

setData(json);

fetchData();

}, []);

return <div>{[Link](item => [Link])}</div>;

In this example, the useEffect hook is used to fetch data from an API and update the
state of the component when the data is received. The empty array [] passed as the
second argument to useEffect means that the effect does not depend on any values
and will only run once, when the component is first rendered.

The use of dependency in useEffect is to re-run the effect whenever the values in the
dependency array change, this allows react to re-render the component and update
the state accordingly. If the dependency array is empty or not provided, the effect will
run only on the first render and not on re-render.

Here is an example of how to use useEffect with a dependency:

function MyComponent({id}) {

const [data, setData] = useState([]);

useEffect(() => {
async function fetchData() {

const response = await fetch([Link]

const json = await [Link]();

setData(json);

fetchData();

}, [id]);

return <div>{[Link](item => [Link])}</div>;

In this example, the `useEffect` hook is used to fetch data from an API based on the
`id` prop passed to the component. The `id` prop is included in the dependency
array, which means that the effect will re-run whenever the `id` prop changes. This
allows the component to update the data displayed in the UI when the `id` prop
changes.

In summary, `useEffect` is a hook in React that allows you to synchronize a


component with an external system, such as a browser API or a back-end service.
The use of dependency in `useEffect` is to re-run the effect whenever the values in
the dependency array change, this allows react to re-render the component and
update the state accordingly.

Q16 - Explain relation between usecontext hook and redux toolkit?

useContext is a hook in React that allows you to access context from a functional
component, while Redux is a library that provides a way to manage the state of an
application in a centralized location, known as the "store."

useContext allows you to share state and functions between components without
passing props down through the component tree. Instead, you can create a context
object with a default value and a provider component that wraps the components
that need access to the context. The consumer components can then use the
useContext hook to access the context.

On the other hand, Redux provides a way to manage the state of an application in a
centralized store. This store can be updated only by dispatching actions, which are
objects that describe a change to the state. The store will then pass the action
through a set of "reducers," which are functions that update the state based on the
action.
Redux Toolkit is a set of tools that makes it easier to use Redux in a project, it
provides a way to configure a store with the necessary reducers and middlewares, it
also provides a feature called "slice" that allows you to manage specific part of the
application state in a more organized way.

While useContext and useRedux are both used for state management, they are used
for different purposes and at different levels of an application. useContext is typically
used for state management within a component or a group of closely related
components, while Redux is used for global state management across an entire
application.

In summary, useContext is a React hook that allows you to share state and functions
between components, while Redux is a library that provides a way to manage the
state of an application in a centralized location, and Redux Toolkit is a set of tools
that makes it easier to use Redux in a project.

Q17 - what is thunks and saga?

Thunks and Sagas are both middleware for Redux that are used to handle side
effects, such as API calls and data handling, in a more organized and maintainable
way.

A thunk is a function that wraps an action and can perform additional logic before or
after the action is dispatched. In the case of an API call, for example, a thunk might
handle the logic for making the API request, as well as dispatching other actions to
update the state of the application based on the response.

Here is an example of a thunk that makes an API call and dispatches an action to
update the state:

function fetchData() {

return async (dispatch) => {

dispatch({ type: 'FETCH_DATA_START' });

try {

const response = await fetch('[Link]

const data = await [Link]();

dispatch({ type: 'FETCH_DATA_SUCCESS', data });

} catch (error) {

dispatch({ type: 'FETCH_DATA_ERROR', error });

}
};

In this example, the fetchData thunk is an asynchronous function that dispatches an


action with the type FETCH_DATA_START before making the API call. If the API
call is successful, it dispatches an action with the type FETCH_DATA_SUCCESS and
the data received from the API. If the API call fails, it dispatches an action with the
type FETCH_DATA_ERROR and the error received.

A Saga is similar to a thunk, it is a generator function that can be used to handle side
effects, such as API calls, in a more organized and maintainable way.

The main difference between them is the way they handle the flow of the actions,
thunks are just functions and the flow of actions is done by dispatching actions, while
sagas are generator functions that allows you to handle the flow of actions using the
yield keyword, which makes it easier to follow the sequence of actions, and also
allows you to handle errors and cancellation in a more elegant way.

In summary, Thunks and Sagas are both middleware for Redux that are used to
handle side effects, such as API calls and data handling, in a more organized and
maintainable way. They are similar in many aspects, the main difference is that
thunks use dispatching actions to handle the flow of actions while sagas use
generator functions and the yield keyword to handle the flow of actions.

Q18 - how would you handle a event in react?

In React, you can handle events by attaching event listeners to elements in the DOM
using the on syntax. For example, to handle a click event on a button, you would use
the onClick attribute:

function MyComponent() {

const handleClick = () => {

[Link]('Button clicked!');

};

return <button onClick={handleClick}>Click me</button>;

In this example, the handleClick function is an event handler that will be called when
the button is clicked. The onClick attribute is used to attach the event listener to the
button.
It's worth noting that React use camelCase for naming events and use on as a prefix
for the event, for example, onClick, onChange, onMouseEnter, etc.

It's also worth noting that, you can also use arrow functions as event handlers, but
it's not recommended as it will create a new function every time the component re-
renders and will cause unnecessary re-renders, it's better to define event handlers as
class methods or use useCallback hook if using functional components.

function MyComponent() {

const handleClick = useCallback(() => {

[Link]('Button clicked!');

}, []);

return <button onClick={handleClick}>Click me</button>;

Q19 - Create a simple react apllication, that swaps any two images when I click on the
any one of the images?

import React, { useState } from 'react';

function ImageSwap() {

const [image1, setImage1] = useState('[Link]');

const [image2, setImage2] = useState('[Link]');

const handleImage1Click = () => {

setImage1(image2);

setImage2(image1);

};

const handleImage2Click = () => {

setImage1(image2);

setImage2(image1);
};

return (

<div>

<img src={image1} onClick={handleImage1Click} alt="Image 1" />

<img src={image2} onClick={handleImage2Click} alt="Image 2" />

</div>

);

export default ImageSwap;

In this example, the ImageSwap component contains two state variables, image1 and
image2, which are used to store the URLs of the images. The component also
contains two event handlers, handleImage1Click and handleImage2Click, that are
used to swap the images when either image is clicked.

The handleImage1Click function is called when the first image is clicked and it uses
the setImage1 and setImage2 state variables to swap the images. The
handleImage2Click function is called when the second image is clicked and it also
uses the setImage1 and setImage2 state variables to swap the images.

You can replace the [Link] and [Link] with URLs of your own images and
the component will work as expected.

It's worth noting that this code is just an example, in a real world application you
may want to handle more complex logic like checking for the current images being
displayed, handling errors in case the images are not loaded, or even using a library
like react-swipeable to handle the swipe events.

Q20 - What are Hooks and it's uses? Tell me about different hooks?

Hooks are functions in React that allow you to use state and other React features in
functional components. They were introduced in React 16.8 as an alternative to class-
based components. They make it easy to reuse stateful logic and avoid the need for
creating higher-order components or render props.

Hooks are used to manage the state and side effects in functional components, and
they're also used for code organization.

Here are some of the most commonly used hooks in React:


 useState: allows you to add state to a functional component. It returns an
array with two elements: the current state and a setter function to update the
state.

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

 useEffect: allows you to synchronize a component with an external system,


such as a browser API or a back-end service. It allows you to run side effects,
such as fetching data or setting up event listeners, in a functional component.

useEffect(() => {

[Link] = `You clicked ${count} times`;

}, [count]);

 useContext: allows you to access context from a functional component. It


receives a context object and returns the current context value for that
context.

const theme = useContext(ThemeContext);

 useReducer: allows you to handle complex state updates and it's similar to the
useState hook but it's more powerful, it's a way to handle state updates in a
way similar to using a reducer in Redux.

const [state, dispatch] = useReducer(reducer, initialArg, init);

 useCallback: allows you to optimize the performance of your component by


avoiding unnecessary re-renders. It returns a memoized callback.

const memoizedCallback = useCallback(() => {

doSomethingExpensive();

 }, [dependency1, dependency2]);
 useMemo : allows you to memoize expensive calculations and avoid re-
calculating them on every render. It returns a memoized value.
 const memoizedValue = useMemo(() => expensiveCalculation(a, b), [a, b]);

There are many other hooks available in React, such as:

 useRef: allows you to create a reference to a DOM element or a React


component instance, which can be used to access the underlying DOM
element or component instance.

const inputRef = useRef(null);


Hooks are a powerful feature of React that allows you to build reusable and
maintainable code, by allowing you to manage state and side effects in functional
components, and make it easy to share stateful logic between components.

It's worth noting that hooks should only be called at the top level of a component,
and should not be called inside loops or conditions, this is because hooks rely on the
order in which they are called, and calling them in the wrong order could lead to
unexpected behavior or errors.

Also, it's worth noting that hooks are a relatively new feature and are still being
developed, so it's important to stay up to date with any new hooks or updates to
existing hooks that may be released in future versions of React.
React - FAQ Set 2
__________________________________________________________
__

Q1 : Explain your understanding of react router DOM?

React Router DOM is a library that allows you to handle client-side routing in a React
application. It provides a way to map URLs to components, and manage the
browser's history so that you can navigate between different parts of your app
without a full page reload. This allows you to create a seamless user experience and
improve the performance of your application. React Router DOM provides a set of
components, such as <Link> and <Route>, that you can use to build your
application's routing structure.

Q2 : What do you understand about the Higher order component in React?

A Higher-Order Component (HOC) is a pattern in React where a component is used


to wrap another component in order to reuse component logic. HOCs are a way to
share component logic across multiple components, rather than duplicating that
logic in every component that needs it.

A higher-order component is a function that takes a component and returns a new


component. The new component has access to the props of the wrapped component,
and can also receive additional props of its own. The new component can then render
the wrapped component, with the added ability to render additional markup or
behavior.

HOCs are a powerful way to handle component reuse, abstract component logic, and
share logic across multiple components. They are also useful for adding additional
functionality, such as authentication or performance optimization, to existing
components.

One example of a common use of HOCs is to handle authentication. A HOC that


handles authentication can be used to wrap multiple components, and it will ensure
that a user is logged in before displaying the wrapped component.

Q3 : Difference between useState and useEffect ?

useState and useEffect are both hooks in React that allow you to add functionality to
your functional components. However, they serve different purposes and are used in
different ways.

useState is used for managing state in a functional component. It allows you to add
state to your component, and update it in response to user interactions or other
events. It returns an array with two elements: the current state value, and a function
that can be used to update the state.
useEffect is used for managing side-effects in a functional component. A side-effect is
any behavior that is not directly related to the component's rendering, such as data
fetching, subscriptions, or browser APIs. It allows you to perform these actions in
response to changes in the component's state or props. It takes a callback function as
an argument, which will be called after the component has rendered.

In short, useState is used to handle the state of a component, whereas useEffect is


used to handle the side effects of a component such as fetching data, subscriptions or
browser APIs.

Q4 : Task - Make a prime number checker in react?

Here's an example of a simple React component that checks if a number is prime:

import React, { useState } from 'react';

const PrimeChecker = () => {


const [number, setNumber] = useState(0);
const [isPrime, setIsPrime] = useState(false);

const handleChange = (event) => {


setNumber([Link]);
}

const checkPrime = () => {


if (number < 2) {
setIsPrime(false);
return;
}

for (let i = 2; i <= [Link](number); i++) {


if (number % i === 0) {
setIsPrime(false);
return;
}
}
setIsPrime(true);
}

return (
<div>
<input type="number" value={number} onChange={handleChange} />
<button onClick={checkPrime}>Check Prime</button>
<p>{isPrime ? 'Prime' : 'Not Prime'}</p>
</div>
);
};

export default PrimeChecker;


This component has a number input field and a button to check if the number
entered is prime or not. It uses the useState hook to manage the state of the number
and whether or not it's prime. The handleChange function updates the number state
with the value of the input field when the user types in it. The checkPrime function,
called by the button, checks if the number is prime and updates the state accordingly.
It's a simple example of how to check if a number is prime in react.

Q5 : How to achieve life-cycle methods in functional components?

In React, class-based components have built-in lifecycle methods that are triggered
at specific points during the component's lifecycle, such as when it's mounted,
updated, or unmounted.
Functional components, on the other hand, do not have built-in lifecycle methods.
However, you can achieve similar functionality in functional components by using
React Hooks.

The useEffect hook is the equivalent of lifecycle methods like componentDidMount,


componentDidUpdate, and componentWillUnmount. It allows you to run side-
effects, such as data fetching or subscriptions, at specific points during the
component's lifecycle.

Here's an example of using useEffect to simulate componentDidMount:


import { useEffect } from 'react';

const MyComponent = () => {


const [data, setData] = useState(null);

useEffect(() => {
fetch('[Link]
.then(response => [Link]())
.then(data => setData(data))
}, []); // only run on the initial mount

return <div>{data}</div>
}

In this example, the useEffect hook is used to fetch data from an API when the
component is first mounted. The empty array [] passed as the second argument to
useEffect ensures that the effect only runs on the initial mount of the component,
which is similar to the componentDidMount lifecycle method.

You can also use the useEffect to simulate componentDidUpdate by passing a


dependency array of the state/props that you want to listen on.

In short, you can achieve lifecycle methods in functional component using useEffect
hook by using the dependencies array and comparing the current state/props with
the previous state/props.

Q6 : Does Browser read JSX directly?

No, the browser does not read JSX directly.


JSX is a syntax extension for JavaScript, it is not a standalone language and it is not
understood by the browser.
In order for the browser to be able to understand and render your React code, it
needs to be transformed from JSX to plain JavaScript.
This is typically done using a transpiler such as Babel, which converts JSX into
regular JavaScript that the browser can understand.

When you use JSX in a React application, the transpiler will convert it into regular
JavaScript function calls or objects that correspond to the elements and components
you've defined.
For example, the following JSX code:

<h1>Hello, World!</h1>

Will be transpiled into this JavaScript code:

[Link]("h1", null, "Hello, World!");

In summary, JSX is not directly understood by the browser, it needs to be transpiled


to JavaScript before it can be run by the browser.

Q7 : What is DOM and how is it related to react?

The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It represents the structure of a document as a tree-like object, with each
element and attribute in the document represented as a node in the tree. The DOM
allows you to manipulate the content and structure of a document, as well as respond
to events that occur in the document, such as user interactions.

React is a JavaScript library for building user interfaces. React uses the concept of a
virtual DOM, which is a representation of the actual DOM in memory. When you
build a React application, React creates a virtual DOM and uses it to update the
actual DOM in the browser.

React uses the virtual DOM to optimize updates to the actual DOM. When a
component's state or props change, React updates the virtual DOM and then
performs a "diff" to determine which parts of the actual DOM need to be updated.
This process is more efficient than updating the entire DOM every time something
changes, and it helps to improve the performance of React applications.

In summary, React uses the DOM as the target where it renders the user interface,
but it uses a virtual representation of the DOM to optimize the updates and improve
the performance of the application.

Q8 : Explain different ways to manage states in react?

There are several different ways to manage state in a React application, including:
 useState hook: This is the most basic way to manage state in a functional
component. It allows you to add state to a component and update it in
response to user interactions or other events. It returns an array with two
elements: the current state value, and a function that can be used to update
the state.
 useReducer hook: This is similar to useState but it's more powerful and it's
more suitable for complex and large state. It allows you to manage state in a
way that's similar to using a reducer function with the dispatch method in
Redux.
 context: This allows you to share state between components without having to
pass props down through multiple levels of the component tree. It's useful
when you want to share state that's not directly related to the current
component, but it can be complex to implement and it's not recommended to
use it unless you really need it.
 Redux: A popular state management library that allows you to manage the
state of your entire application in a centralized store. It uses a reducer
function to update the state and actions to trigger updates. It can be overkill
for simple application but it's very useful for larger and more complex
applications.
 Mobx: A state management library similar to Redux, but it uses a more
reactive approach and it's more focused on performance. It's also a good
option for larger and more complex applications.

In short, for small and simple applications, useState hook is enough, for complex and
large application, useReducer or external libraries such as Redux or Mobx is
recommended.
It's also worth noting that it's not always necessary to use a library for state
management, it depends on the complexity and size of the application and the
developer's preference.

Q9 : How can you find all the missing numbers between 1 and 50 in an array of
random elements in React?

There are different ways to find missing numbers in an array of random elements in
React, but one possible approach is to use the [Link]() and
[Link]() methods to create a new array that contains only the
missing numbers:

const randomArray = [10, 30, 20, 40, 35, 45, 15];


const set = new Set(randomArray)
const missingNumbers = [Link](new Array(50), (_, i) => i + 1)
.filter(num => ![Link](num));
[Link](missingNumbers);

You can use this approach to find missing numbers in a functional component and
use it in your application as per your requirement.

In short, you can use Array's filter() and includes() or Set's has() method to find the
missing numbers in an array of random elements in React.
Q10 : Can we fetch data without using hooks in react?

Yes, it is possible to fetch data without using hooks in React. In class-based


components, you can use lifecycle methods such as componentDidMount to fetch
data and update the component's state when the component is first rendered.

Here's an example of fetching data in a class-based component using the


componentDidMount lifecycle method:

class MyComponent extends [Link] {


constructor(props) {
super(props);
[Link] = {
data: null
};
}

componentDidMount() {
fetch("[Link]
.then(response => [Link]())
.then(data => [Link]({ data }));
}

render() {
return <div>{[Link]}</div>;
}
}

This component fetches data from an API when it's first mounted and updates the
component's state with the response data. The component will re-render and show
the data when it's available.

It's worth noting that, functional component with hooks has many advantages over
class-based component such as being more concise, and easier to test, reason hooks
are recommended by React team. But still, you can use class-based component to
fetch the data and update the component's state.

Q11 : Create search box (It should display all the products of the same name) in
react?

Here is an example of a simple search box component that filters an array of


products based on the name:

import React, { useState } from 'react';

const SearchBox = ({ products }) => {


const [searchTerm, setSearchTerm] = useState('');
const [filteredProducts, setFilteredProducts] = useState(products);

const handleChange = (event) => {


setSearchTerm([Link]);
}

useEffect(() => {
const results = [Link](product =>
[Link]().includes([Link]())
);
setFilteredProducts(results);
}, [searchTerm, products]);

return (
<div>
<input type="text" value={searchTerm} onChange={handleChange}
placeholder="search product" />
<ul>
{[Link](product => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
};

export default SearchBox;

This component receives an array of products as a prop, and it uses the useState
hook to manage the state of the search term, and the filtered products.
The handleChange function is used to update the state of the search term as the user
types in the input field.
The useEffect hook is used to filter the products based on the search term, it
compares the searchTerm with the name of products, if it matches it will be added to
the filteredProduct array.
It also uses the map method to render the filtered products in an unordered list.

You can use this component in other parts of your application and pass the products
array to it as a prop.

In summary, this component uses the useState hook to manage the state of the
searchTerm, filteredProducts and useEffect hook to filter the products based on the
searchTerm, it's a simple example of how you can create a search box in React.

Q12 : Why we use react instead of Html & CSS?

React is a JavaScript library for building user interfaces, while HTML and CSS are
markup languages and stylesheet languages respectively. React provides a number of
advantages over using just HTML and CSS to build web applications:

 Reusability: React allows you to create reusable components that can be used
across your application. This promotes modularity and helps to keep your
code organized and maintainable.
 State Management: React allows you to manage the state of your application
in a centralized and efficient way. This makes it easy to update the UI when
the state changes and it also makes it easy to manage complex interactions
and data flow.
 Performance: React uses a virtual DOM to optimize updates to the actual
DOM. This process is more efficient than updating the entire DOM every time
something changes, and it helps to improve the performance of React
applications.
 JSX: React uses JSX, which is a syntax extension for JavaScript. It allows you
to define components using a familiar syntax that looks similar to HTML. This
makes it easy to understand and write the code, especially for developers who
are familiar with HTML.
 Dynamic & Interactive: React provides a way to create dynamic and
interactive user interfaces, this is not possible with just HTML & CSS.
 Community: React has a large and active community, which means there are
many resources available to help you learn and use React, including tutorials,
documentation, and third-party libraries.

In short, React provides a powerful and efficient way to build web applications with
reusable components, state management, performance optimization, JSX and a large
community

Q13 : Why use render in the component?

In React, the render method is used to define the structure and content of a
component. It is called whenever the component's state or props change, and it's
responsible for returning a description of the component's UI.

The render method is a required part of any React component, it's the core of how
React works. It's called when the component is first created, and it's also called
whenever the component's state or props change. React uses the result of the render
method to update the actual DOM and reflect the changes in the UI.

The render method is a pure function, which means it should not have any side-
effects, such as modifying the component's state or interacting with the browser
APIs. It should only return a description of the component's UI based on its props
and state.

The render method is also where you define the structure and content of the
component, using JSX. JSX is a syntax extension for JavaScript that allows you to
define the structure of the component using a familiar syntax that looks similar to
HTML.

In short, render method is used to define the structure and content of the
component, it's responsible for returning a description of the component's UI and it's
called whenever the component's state or props change, React uses the result of the
render method to update the actual DOM and reflect the changes in the UI.

Q14 : How to increment value on button click using usestate?


You can use the useState hook in a functional component to increment a value on
button click. Here's an example:

import { useState } from 'react';

const MyComponent = () => {


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

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

In this example, the component uses the useState hook to define a count state
variable with an initial value of 0. The component renders a paragraph element that
displays the current count value, and a button element that when clicked calls the
setCount function and increments the value by 1.

You can also use the shorthand operator ++ to increment the value

<button onClick={() => setCount(count => count + 1)}>Increment</button>

In summary, to increment a value on button click using useState you need to define a
state variable with the useState hook, render a button element and call the setter
function of the state variable in the onClick event of the button and pass the updated
value.

Q15 : How to change port in react app?

The default port for a React app created using create-react-app is 3000. However,
you can change the port to a different one by following these steps:

 Open the [Link] file in the root of your React app.


 In the "scripts" section, locate the "start" script, it should look something like
this:
"start": "react-scripts start"
 Replace "react-scripts start" with "react-scripts start --port your-new-port"
"start": "react-scripts start --port your-new-port"
 Save the changes and run the app using the new port.
npm start or yarn start

It's also worth noting that if the port is already in use, it will throw an error. in that
case you have to change it to a new port number or stop the process that is running
on that port.

Another way to change the port is by using the .env file, you can create a .env file in
the root of your project and set the PORT variable like this
PORT=3001

This way you can change the port without modifying the [Link] file.

In summary, to change the port in a React app

Q16 : Create a react app of stop watch with min,sec and hours?

Here is an example of a simple stopwatch component that uses the useState and
useEffect hooks to keep track of the minutes, seconds, and hours:

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

const Stopwatch = () => {


const [minutes, setMinutes] = useState(0);
const [seconds, setSeconds] = useState(0);
const [hours, setHours] = useState(0);
const [isRunning, setIsRunning] = useState(false);

useEffect(() => {
let interval = null;
if (isRunning) {
interval = setInterval(() => {
if (seconds < 59) {
setSeconds(seconds + 1);
} else if (minutes < 59) {
setMinutes(minutes + 1);
setSeconds(0);
} else if(hours < 23){
setHours(hours + 1);
setMinutes(0);
setSeconds(0);
}
}, 1000);
} else if (!isRunning && seconds !== 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isRunning, minutes, seconds, hours]);

return (
<div>
<p>{hours < 10 ? `0${hours}` : hours } : {minutes < 10 ? `0${minutes}` :
minutes } : {seconds < 10 ? `0${seconds}` : seconds }</p>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? 'Stop' : 'Start'}
</button>
<button onClick={() => {
setMinutes(0);
setSeconds(0);
setHours(0);
}}>
Reset
</button>
</div>
);
};

export default Stopwatch;

In this code, the component uses the useEffect hook to set an interval that updates
the minutes, seconds and hours state variables every second. The isRunning state
variable is used to control the interval, so it starts and stops when the start/stop
button is clicked. The component also has a reset button that sets the minutes,
seconds, and hours back to 0 when clicked.

The component also uses ternary operator to add leading zeroes to the hours,
minutes, and seconds value if they are less than 10, this way it will look like a regular
stopwatch.

This is a simple example of a stopwatch component that uses the useState and
useEffect hooks in React, you can customize it according to your requirement.

Q17 : Why do we use [Link]?

[Link]() is a method that is used to prevent the default behavior of an


event from occurring.

When an event such as a form submission or a link click happens, the browser will
perform a default action, such as submitting the form or navigating to the link's href.
Calling [Link]() prevents the browser from performing that default
action.

For example, in a form submission, [Link]() is used to stop the form


from submitting to the server and refreshing the page. Instead, it allows you to
handle the form submission with JavaScript, such as displaying an error message or
sending an AJAX request.

Another example is when you are using <a> tag, by default the browser will navigate
to the link's href when you click on it. If you want to handle the click event using
JavaScript, you can call [Link]() to stop the browser from navigating
to the link's href.

It's also possible to use the [Link]() method to stop the event from
propagating to parent elements. It's especially useful when you have nested elements
and you want to handle the event on the specific element, and not the parent
element.

In summary, [Link]() is used to prevent the default behavior of an


event from occurring, it allows you to handle the event using JavaScript and it's
commonly used in form submission, link clicks and other events that have a default
behavior.

Q18 : What are the limitations of react?

React is a powerful and widely-used JavaScript library for building user interfaces,
but like any technology, it has its limitations. Some of the limitations of React are:

 Complexity: React can be complex for beginners to learn and use, especially if
you are new to JavaScript and web development. Understanding the concepts
such as JSX, Virtual DOM, and component lifecycle can be challenging.

 Steep learning curve: React has a steep learning curve, you need to learn the
basics of the library before you can start building more complex applications.

 Overhead: React can add an extra layer of complexity to your application,


especially if you are using other libraries or frameworks. This can lead to
performance issues and increased development time.

 Lack of guidance: React is a flexible library and provides a lot of freedom to


developers, but sometimes this freedom can lead to confusion. There's no
clear guidance on how to structure your code, so you may have to figure it out
yourself.

 Server-side rendering: React can be challenging to set up for server-side


rendering, which can be an issue for some applications.

 Re-rendering: React's automatic re-rendering can be a limitation in certain


situations, for example, when you have a large amount of data and you want to
avoid unnecessary re-renders.

 SEO: React's initial load time is slower than traditional websites, which can be
an issue for search engines when trying to crawl and index your website.

These are some limitations of React, it's worth noting that these limitations are not
unique to React, and many of them can be mitigated by using appropriate
techniques, libraries, or frameworks. Additionally, React is constantly evolving and
improving. The React team and community are working to mitigate these limitations
and make the framework more accessible and efficient.

Q19 : "props are mutable", is this statement true?


The statement "props are mutable" is not entirely true. In React, props (short for
"properties") are passed down from a parent component to a child component and
are used to configure the child component.

Props are considered to be a "single-direction" flow of data, which means that they
are passed down from a parent component to a child component and should not be
modified by the child component. This is because the parent component is
responsible for managing the state of the props and any changes made by the child
component could lead to unexpected behavior.

When a parent component changes its state, it will pass the new state as props to its
children, which will trigger a re-render of the child component. This is the correct
way to update the child component with new data.

So technically speaking, the props are not mutable, they are read-only. React
components are designed to be immutable, this is a key feature that allows React to
efficiently update the UI. If the child component wants to change the prop passed to
it, it should pass the change to the parent component and let the parent component
update the state and pass the new state to the child component.

It is possible to mutate the props in a component but it's generally considered to be


an anti-pattern and discouraged. This is because it can lead to confusion and
unexpected behavior, making it difficult to understand how the component works
and to debug it.

In summary, Props are not mutable, they are passed down from parent component to
child component and should be treated as read-only by the child component.
Changing props in child component directly is not recommended and it's considered
as an anti-pattern.

Q20 : What are the Restful API's and its advantages?

REST (Representational State Transfer) is a set of architectural principles and a set


of constraints that are usually applied to web services. RESTful APIs are web services
that are built using the REST architectural style.

RESTful APIs typically use the HTTP protocol for communication and transfer data
using the JSON or XML format. They typically have a base URL, and the endpoints
of the API are usually a part of the URL.

Advantages of RESTful APIs are :

Scalability: RESTful APIs are lightweight and easy to scale, which makes them a good
choice for large-scale projects.

Language-independent: RESTful APIs can be accessed and consumed by any


programming language that can make HTTP requests and parse JSON or XML
responses.
Stateless: RESTful APIs are stateless, which means that the server does not keep
track of the state of the client. This makes them easy to cache and improves the
performance of the API.

Easy to Test: Since RESTful APIs are based on the HTTP protocol, they can be easily
tested using tools like Postman.

Loosely coupled: RESTful APIs are loosely coupled, which means that the client and
server do not need to know anything about each other. This makes it easy to change
the implementation of one without affecting the other.

Easy to document: RESTful APIs have a well-defined structure, which makes them
easy to document.

Caching: RESTful APIs can be cached, which means that the server can store the
response to a request and reuse it when the same request is made again. This
improves the performance of the API.

In summary, RESTful APIs are a way to build web services that are lightweight,
scalable, language-independent, stateless, easy to test, loosely coupled, and easy to
document. They use the HTTP protocol for communication, and transfer data using
JSON or XML format. These characteristics make RESTful APIs a popular choice for
building web-based applications and services.
NodeJS- FAQ Set 1
__________________________________________________________
__

Q1 - What is NodeJs?

[Link] is an open-source, cross-platform JavaScript runtime environment


that executes JavaScript code outside of a web browser. It allows developers to
run JavaScript on the server side to build fast and scalable network
applications. [Link] uses an event-driven, non-blocking I/O model, which
makes it lightweight and efficient for data-intensive real-time applications that
run across distributed devices. It is commonly used for building web servers,
real-time applications, and command-line tools.

Q2 - What is NPM and Explain its role in Backend?

NPM (Node Package Manager) is the default package manager for [Link],
which is a popular platform for building back-end web applications. NPM
makes it easy for developers to manage the dependencies of their [Link]
projects.

When building a backend application, developers often use various libraries,


frameworks, and modules to perform specific tasks. These libraries are often
open-source and available on the NPM registry, which is a large database of
JavaScript packages. NPM allows developers to easily download and use these
packages in their projects, without having to write all the code themselves.

The role of NPM in Backend is to manage and install the packages required for
the project, it also helps to keep track of versioning and updates of the
packages. It also allows developers to share their own packages with the
community.

In summary, NPM plays a crucial role in the backend development process by


allowing developers to easily manage dependencies, share code and make use
of existing libraries and modules, making the development process faster and
more efficient.
Q3 - Why do we use NodeJs?

[Link] is used for a variety of reasons, some of the most common ones are:

Speed: [Link] is built on Google's V8 JavaScript engine, which is known for


its speed and performance. This makes it well-suited for building fast and
scalable network applications.

Asynchronous and Event-Driven: [Link] uses an event-driven, non-blocking


I/O model, which makes it lightweight and efficient for data-intensive real-
time applications that run across distributed devices.

JavaScript on the server-side: [Link] allows developers to run JavaScript on


the server-side, which means that the same language can be used for both the
front-end and back-end of an application. This can simplify the development
process and reduce the learning curve for developers who are already familiar
with JavaScript.

Large and active community: [Link] has a large and active community, which
means that there are many resources available for learning and
troubleshooting. There are also a lot of packages available on the npm registry,
which can be easily integrated into [Link] projects.

Microservices: [Link] is a good fit for building microservices architecture,


where the application is split into small, independent services that
communicate with each other. [Link] is lightweight, fast and easy to work
with, making it an ideal option for building microservices.

Cross-Platform Compatibility: [Link] is cross-platform and can run on


various operating systems, including Windows, Mac, and Linux. This makes it
easy to develop and deploy [Link] applications on different platforms.

Popularity: [Link] is widely used in various industries and has been gaining
popularity in recent years. It is used by many popular companies such as
Netflix, Uber, PayPal, and more.

Q4 - What are http codes? Can you explain a few commonly used http codes?

HTTP codes, also known as HTTP status codes, are three-digit numbers that
are used to indicate the status of a request made to a web server. They provide
information about whether the request was successful, and if not, what kind of
error occurred.
Here are a few commonly used HTTP codes:

200 OK: This code indicates that the request was successful and the server has
returned the requested data.

201 Created: This code indicates that a new resource has been successfully
created as a result of the request.

204 No Content: This code indicates that the request was successful, but there
is no data to return.

400 Bad Request: This code indicates that the request was malformed or
otherwise incorrect. It may be caused by issues such as missing required
parameters or invalid syntax.

401 Unauthorized: This code indicates that the request was not authorized. It
may be caused by an incorrect or missing authentication token.

403 Forbidden: This code indicates that the server understood the request, but
it refuses to authorize it. It may be caused by the user not having the necessary
permissions to access the requested resource.

404 Not Found: This code indicates that the requested resource could not be
found on the server.

500 Internal Server Error: This code indicates that an error occurred on the
server and the request could not be completed.

503 Service Unavailable: This code indicates that the server is currently
unavailable due to maintenance or high traffic.

These are just a few examples of the many different HTTP codes that exist.
Each code has a specific meaning and can provide important information
about the status of a request.

Q5 - How would you handle errors in the backend?

Handling errors in the back-end of an application is important to ensure that


the application continues to function properly and that users are provided
with clear and informative error messages. Here are a few common ways to
handle errors in the back-end:

Try-Catch Blocks: Try-catch blocks are a built-in feature of many


programming languages, including JavaScript, that allow you to catch and
handle errors that occur within the try block. This can be useful for handling
errors that occur within a specific function or section of code.

Error-First Callbacks: Error-first callbacks are a common pattern in [Link]


where the first argument passed to a callback function is an error object. This
allows you to easily check for errors and handle them appropriately.

Global Error Handling: In some cases, it may be useful to have a global error
handler that is called whenever an error occurs. This can be useful for logging
errors, sending notifications or handling errors that might occur in unexpected
places in the code.

HTTP status codes: It is a good practice to return appropriate HTTP status


codes to indicate the status of the request and if there's any error.

Logging: Logging errors is an important aspect of error handling. It helps to


track the error, and it also helps to identify and debug the issues.

Notify: It is important to notify the related parties when an error occurs, so


that they can take appropriate action as soon as possible.

It's also important to note that different types of errors may require different
types of handling. For example, a validation error may require a different
response than a server-side error. It's important to have a clear understanding
of the different types of errors that may occur and to handle them accordingly.

Q6 - What is Express?

Express is a popular and widely-used JavaScript web application framework


for [Link]. It is built on top of [Link] and provides a flexible set of features
for web and mobile applications. Express provides a minimal and flexible core
web application framework that allows developers to build robust and scalable
web applications and APIs.

Express allows developers to handle HTTP requests and responses, define


routes, handle middleware, and more. It simplifies the process of building web
applications by providing a simple and flexible API for handling common web
development tasks. Express also provides a built-in router, which makes it
easy to handle different routes and endpoints in your application.

Express also supports middleware which are the functions that have access to
the request object (req), the response object (res), and the next middleware
function in the application's request-response cycle. These functions are
executed sequentially and they can perform various tasks like parsing the
request body, checking authentication, logging, etc.

Express is a popular choice for building web applications and APIs because it
is fast, lightweight, and easy to use. It is well-documented, has a large and
active community, and has a wide range of third-party modules and plugins
available to extend its functionality.

Q7 - Difference between ExpressJS and NodeJS?

[Link] and [Link] are both JavaScript technologies, but they serve
different purposes.

[Link] is a JavaScript runtime environment that allows developers to run


JavaScript on the server side. It is a platform that provides an event-driven,
non-blocking I/O model, making it lightweight and efficient for data-intensive
real-time applications. [Link] is built on the V8 JavaScript engine and
provides an API for interacting with the operating system, file system, and
network.

[Link], on the other hand, is a web application framework for [Link]. It is


built on top of [Link] and provides a flexible set of features for web and
mobile applications. Express provides a minimal and flexible core web
application framework that allows developers to build robust and scalable web
applications and APIs. It provides a simple and flexible API for handling
common web development tasks, such as handling HTTP requests and
responses, defining routes, handling middleware and more.

In simple terms, [Link] is the platform and [Link] is a framework built on


top of it, to make web development with [Link] easy and efficient. You can
use [Link] to build command-line tools, scripts, and other types of
applications, but when it comes to web development, using [Link] is the
common choice.

In short, [Link] is a JavaScript runtime environment, while [Link] is a


web application framework for [Link]. [Link] is used to execute JavaScript
on the server side, while [Link] makes it easy to build web applications and
APIs using [Link].

Q8 - If you were asked to create a server, how would you do it NodeJS?

If I were asked to create a server using [Link], I would follow these steps:

First, I would create a new project directory and initialize it using npm (Node
Package Manager) by running "npm init" in the command line. This will create
a [Link] file, which will contain information about the project, including
the dependencies.

Next, I would install the "http" module, which is a built-in module in [Link],
by running "npm install http" in the command line. This module provides a
simple API for creating HTTP servers and clients.

In the project directory, I would create a new JavaScript file, for example,
"[Link]" which will contain the server logic.

In the [Link] file, I would import the http module using the require()
function and create a new instance of the HTTP server by calling the
[Link]() method.

I would then define the behavior of the server by defining a callback function
that will be called every time a request is made to the server. This function will
take in two arguments: a request object (req) and a response object (res).

Inside the callback function, I would use the request object to access
information about the incoming request, such as the method, headers, and
body. I would use the response object to set the response status code and
headers, and to send the response body.

Next, I would make the server listen to a specific port by calling the listen()
method on the server instance and passing in the port number as an
argument.

Finally, I would start the server by calling the server's listen method and
passing the port number and a callback function that will be called when the
server is successfully listening.

Example code:
const http = require('http');
const server = [Link]((req, res) => {
[Link] = 200;
[Link]('Content-Type', 'text/plain');
[Link]('Hello World\n');
});
const port = 3000;
[Link](port, () => {
[Link](`Server running at [Link]
});

This is a simple example of creating a server using [Link], in a real-world


scenario, a framework such as Express can be used to make the process more
easier, handle errors and provide more functionalities.

Q9 - Why did you use Nodemon?

Nodemon is a utility that automatically restarts a [Link] application when


changes are made to the source code. It is particularly useful for development
purposes, as it eliminates the need to manually stop and start the server every
time changes are made.

Nodemon is not a built-in [Link] module, it needs to be installed separately.


Once installed, you can use it in place of the node command to run your
application. Nodemon will monitor the source code for changes and
automatically restart the server when it detects any changes.

Some of the benefits of using Nodemon are:

 Saves time by automatically restarting the server when changes are


made
 Reduces the risk of errors caused by forgetting to restart the server after
making changes
 Helps to speed up the development process by allowing developers to
see the results of their changes immediately

It's important to note that Nodemon is intended for development use only, it is
not recommended to use it in a production environment.

Q10 - What is CORS? Give a practical example on where you require it?
CORS (Cross-Origin Resource Sharing) is a security feature implemented by
web browsers that blocks web pages from making requests to a different
domain than the one that served the web page. This is done to prevent
malicious websites from making unauthorized requests to a user's data.

For example, imagine you have a website that serves content from
[Link], and it makes an API call to [Link] to retrieve some
data. This will be blocked by the browser by default as it is a cross-origin
request.

CORS allows a server to relax the same-origin policy and allow a web page
from one origin (domain) to access resources from another origin. This is done
by adding certain headers to the server's response, such as "Access-Control-
Allow-Origin", which tells the browser which origin(s) are allowed to access
the resources.

A practical example of where CORS is required would be a web application


that serves a user interface from one origin ([Link]) and an API from
another origin ([Link]). In this case, the web application would
need to make requests to the API to retrieve data. Without CORS, the browser
would block these requests. By configuring CORS on the API server, the
browser can be told that it is safe to allow these requests and the application
can function as intended.

CORS can be configured on the server-side by setting the appropriate headers


in the response, such as "Access-Control-Allow-Origin", "Access-Control-
Allow-Methods" and "Access-Control-Allow-Headers", etc.

It's important to note that CORS is a security feature, and while it allows
different domains to communicate, it also imposes some restrictions to
prevent malicious sites from accessing sensitive data.

Q11 - Make a get request to [Link]

const express = require('express');


const cors = require('cors');
const axios = require('axios');

const app = express();


[Link](cors());
[Link]('/posts', (req, res) => {
[Link]('[Link]
.then(response => {
[Link]([Link]);
})
.catch(error => {
[Link]({ error: [Link] });
});
});

const port = 3000;


[Link](port, () => {
[Link](`Server running at [Link]
});

In this example, we are using the express framework, and the cors middleware
is added using the [Link](cors()) statement. This middleware automatically
handles the CORS headers, allowing any origin to access the resources. Also,
we are using the axios library to make the request to the API.

In this example, a GET request to the '/posts' route will trigger the function,
which uses axios to make the GET request to the API. If the request is
successful, it will return the data from the API as JSON to the client. If the
request fails, it will return the error message as JSON to the client.

Q12 - Explain your understanding of Middleware?

In the context of web development, middleware refers to software that sits


between the application and the server, and acts as a bridge between them. It
typically provides a set of functions that can be used to perform specific tasks,
such as logging, authentication, or data validation.

Middleware functions are typically executed in the order in which they are
added to the application, and have access to the request and response objects,
as well as the next middleware function in the stack.

A middleware function can perform any of the following tasks:

 Modifying or inspecting the request and response objects


 Terminating the request-response cycle
 Calling the next middleware function in the stack
In Express, middleware functions are added to the application using the
[Link]() or [Link]() method. These functions are executed in the order in
which they are added, and have access to the request and response objects, as
well as the next middleware function in the stack.

For example, you may have a middleware function that checks for an
authentication token in the request headers, and if it's not present, it returns a
401 error, otherwise it calls the next middleware function in the stack.

In summary, middleware is a way to add functionality to a web application


that sits in between the application and the server. It can be used to perform
various tasks like parsing the request body, checking authentication, logging,
etc. Middleware functions are executed sequentially and they have access to
the request and response objects, as well as the next middleware function in
the application's request-response cycle.
Q13 - What is the use of json web token? Where will you use them in your
project?

JSON Web Token (JWT) is a standard for representing claims securely


between two parties. It is typically used for authentication and authorization
in web applications. JWT is a JSON object, which is encoded and signed to
create a compact, self-contained token that can be transmitted securely
between parties.

JWT's are typically used for authentication and authorization in web


applications, allowing for the secure transfer of information between the client
and server. When a user logs in, the server will generate a JWT and send it to
the client. The client will then send this JWT with each subsequent request,
and the server can use it to authenticate the user and authorize access to
protected resources.

One of the advantages of using JWT's is that they can be easily transmitted in
the HTTP headers, which makes them very easy to use in web applications.
JWT's also have the advantage of not requiring the server to store any session
state, which can improve scalability and reduce the risk of data breaches.

In my project, I would use JWT's for authentication and authorization


purposes. For example, when a user logs in, the server will generate a JWT
and send it to the client. The client will then store this JWT in the browser's
local storage or a cookie, and send it with each subsequent request. The server
will then use the JWT to authenticate the user and authorize access to
protected resources.
It's important to note that JWT's should be stored securely on the client side,
and the secret key used to sign the token should be kept secret on the server
side. JWT's should also be encoded and signed, to ensure the authenticity of
the token.

Q14 - What is Bcrypt and where will you use it?

Bcrypt is a password hashing function designed to be computationally


expensive to calculate, making it more resistant to brute force attacks. It is a
one-way function that takes an input (i.e. a password) and generates a fixed-
length string of characters, which is the hashed password. The same input will
always produce the same output, but the output cannot be used to determine
the original input.

When a user signs up or changes their password, the plain text password is
passed through the bcrypt function which generates a hashed password. This
hashed password is then stored in the database.

When a user attempts to log in, the plain text password they entered is passed
through the bcrypt function again, and the result is compared to the stored
hashed password. If they match, the password is considered to be correct and
the user is granted access.

Bcrypt is designed to be computationally expensive to calculate, which makes


it more resistant to brute force attacks than other hashing algorithms. It also
has a built-in mechanism for handling "salt", which is a random data added to
the input to make it harder for an attacker to use precomputed tables of
hashed values.

In my project, I would use bcrypt to hash the user's password before saving it
to the database. This would ensure that even if the database is compromised,
the attacker would not have access to the plain-text password. I would also use
bcrypt to compare the plain-text password entered by the user during login
with the hashed password stored in the database.

Q15 - Difference between PUT and PATCH Methods?

PUT and PATCH are both HTTP methods used to update resources on a
server, but they are used in slightly different ways.
The PUT method is used to completely replace a resource with a new
representation. When a client sends a PUT request, it typically includes the
entire representation of the resource in the request body, and the server is
responsible for replacing the entire resource with the new representation. This
method is idempotent, meaning that multiple identical PUT requests will have
the same effect as a single request.

The PATCH method, on the other hand, is used to partially update a resource.
When a client sends a PATCH request, it typically includes only the changes to
the resource in the request body, and the server is responsible for merging the
changes into the existing resource. This method is not idempotent, and
multiple identical PATCH requests may have different effects depending on
the state of the resource.

An example of when to use PUT is when you want to update a specific


resource, for example when you want to update an entire user's information in
a database, you would use a PUT request with the entire updated user
information.

An example of when to use PATCH is when you want to update only a specific
field of a resource, such as updating only the name of a user in a database, you
would use a PATCH request that includes only the field name and its new
value.

In summary, PUT method is used for replacing a resource entirely and it's
idempotent, while PATCH is used for updating a specific part of a resource
and it's not idempotent.

Q16 - Difference between authentication and authorization, why do we need


both?

Authentication and authorization are two related but distinct concepts in web
application security.

Authentication is the process of verifying the identity of a user or system. It is


the process of determining whether someone or something is, in fact, who or
what it is declared to be. Authentication typically involves a user providing a
set of credentials, such as a username and password, which are then verified
against a database of authorized users.

Authorization, on the other hand, is the process of determining whether a user


or system is allowed to perform a specific action or access a specific resource.
Once the identity of a user or system has been established through
authentication, the application can use this information to determine what
actions the user or system is authorized to perform.

We need both authentication and authorization because, without


authentication, we can't be sure who is accessing our application and its
resources, and without authorization, we can't control what actions they are
allowed to perform.

Authentication ensures that the user is who they claim to be, whereas
authorization ensures that the user is only allowed to perform specific actions
or access specific resources. Together, they provide a complete security
solution by verifying the identity of users and controlling their access to
resources.

Q17 - Explain [Link] vs [Link]?

[Link] and [Link] are both files that are used in [Link]
projects to manage dependencies.

[Link] is a file that contains metadata about the project, such as the
project's name, version, and dependencies. It is used to specify the project's
dependencies, their version numbers, and other information about the project.
The file is typically created by running the command npm init and it contains
various fields like name, version, author, scripts, dependencies and
devDependencies.

[Link], on the other hand, is used to lock down the versions of the
project's dependencies and their dependencies to a specific version. It is
automatically generated when running the npm install command and it
contains the exact version of each dependency installed in the project. This
ensures that the same versions of dependencies are installed on different
machines or when the project is deployed to production.

The main difference between these two files is that [Link] is mainly
used to specify the dependencies and other information about the project,
while [Link] is used to lock down the versions of the dependencies
to specific versions.

When a developer runs the npm install command, npm uses the information
from [Link] to resolve the dependencies and their versions, and then
generates [Link] file that contains the exact versions of all the
packages and dependencies installed in the project.
In summary, [Link] contains the information about the project and its
dependencies, while [Link] contains the exact version of all the
packages and dependencies installed in the project. They both work together
to ensure that the same versions of dependencies are installed on different
machines and in different environments.

Q18 - Is Node js a single threaded or a multithreaded language?

[Link] is a single-threaded language.

In [Link], the JavaScript engine uses a single thread to execute the


JavaScript code. This means that it can only process one task at a time.
However, it can handle multiple tasks by using an event loop, which allows it
to execute multiple asynchronous tasks in a single-threaded environment.

The event loop is a mechanism that allows [Link] to handle multiple tasks by
executing them one at a time. It uses a call stack and a message queue to
manage the execution of asynchronous tasks and ensure that the code runs
smoothly.

While [Link] is single-threaded, it makes use of multiple threads through its


built-in support for asynchronous I/O operations. This allows it to perform
non-blocking I/O operations such as reading/writing to the file system,
network connections etc. It uses multiple threads from the underlying
operating system to perform these operations, which enables it to handle a
large number of concurrent connections.

In summary, [Link] is primarily single-threaded in terms of JavaScript code


execution, but it uses multiple threads to handle I/O operations through its
built-in asynchronous capabilities and event loop.

Q19 - how to validate a user?

There are several ways to validate a user in a web application, depending on


the specific requirements and constraints of the application. Some common
methods include:

Username and password: This is the most common form of validation. Users
enter their username and password, which are then verified against a database
of authorized users. This can be done using bcrypt or other encryption
methods to ensure that the password is stored securely.
Email and password: In this method, users enter their email address and
password, which are then verified against a database of authorized users. This
method is useful if the application allows users to sign up with their email
address rather than a username.

OAuth: OAuth is an open standard for authorization that allows users to


securely sign in to a web application using their existing credentials from
another web application. This method is useful if the application wants to
allow users to sign in with their Google, Facebook, or other social media
accounts.

Two-factor authentication: This method involves a user providing two forms


of identification, such as a password and a fingerprint or a password and a
one-time code sent to their phone.

Captcha: Captcha is a test that is used to ensure that the user is a human and
not a bot. This can be in the form of a puzzle, image or reCAPTCHA.

In addition to these validation methods, it is also important to implement


security measures such as rate limiting, IP blocking, and session management
to prevent brute

Q20 - Explain your understanding of the REST API? What are its alternatives?

REST (Representational State Transfer) is a software architectural style that


defines a set of constraints to be used when creating web services. RESTful
APIs use HTTP requests to POST (create), PUT (update), GET (read), and
DELETE data. A RESTful API is typically composed of a base URL, such as
[Link] and endpoint paths, such as /users, which represent
specific resources.

RESTful APIs have become a popular choice for building web services because
they are simple to understand and easy to consume. However, there are
several alternatives to REST APIs, including:

SOAP (Simple Object Access Protocol): A messaging protocol for exchanging


structured data between applications. SOAP is typically more verbose and
complex than REST, but it also offers more features and security options.

gRPC: A high-performance, open-source framework for building remote


procedure call (RPC) APIs. gRPC uses the Protocol Buffers data format and
supports a wide variety of programming languages.
GraphQL: A query language for your API that allows clients to define the
structure of the data they need, and the server will return only the requested
data. GraphQL is an alternative to REST and SOAP, it gives more control over
data to the client.

WebSockets: A protocol for real-time, bidirectional communication between a


client and a server. WebSockets are often used to build real-time applications,
such as chat and gaming applications, that require low-latency
communication.
NodeJS- FAQ Set 2
__________________________________________________________
__

Q1 : What is fileSystem in Node JS?

The fs (File System) module in [Link] is used to work with the file system on the
computer. It provides a way to read, write, and manipulate files, as well as create and
remove directories. The module can be included in a [Link] script by using the
require() function and specifying fs as the module to be imported. Some common
methods in the fs module include [Link](), [Link](), and [Link]().

Q2 : What are Modules in Node JS?

In [Link], a module is a collection of JavaScript functions and objects that can be


reused across multiple scripts. [Link] provides a built-in module system, which
allows for the creation and use of custom modules as well as the use of pre-built,
third-party modules.

Modules in [Link] are created using the exports object, which is an instance of
[Link]. A module can export one or more functions, objects, or primitive
values that can be imported and used in other scripts using the require() function.

The require() function is used to import a module and access the functionality it
exports. Once a module is imported, the exported functionality can be used as if it
were defined locally in the script.

[Link] also provides a core set of modules that are always available to use in a script
without needing to be imported. Examples of these built-in modules include http, fs,
and path.

The npm package manager makes it easy to find and install additional modules that
can be used in [Link] projects.

Q3 : Is it ok to show JWT in localstorage?

Storing JSON Web Tokens (JWT) in local storage is generally not considered a
secure practice. Local storage is a client-side storage option, meaning that the data
stored in it can be accessed by any JavaScript code running on the same origin. This
means that if an attacker is able to execute arbitrary JavaScript code on the same
origin as your application, they can easily access the JWT stored in local storage.

A more secure option for storing JWT is to use an HTTP-only and secure (HTTPS)
cookie. This will ensure that the JWT can only be accessed by the server and that it is
transmitted over an encrypted connection.
Also, JWT tokens should be kept as short-lived as possible, to minimize the potential
damage if they are compromised. And it should be stored in a secure storage like
HttpOnly cookie or a server-side session storage to prevent cross-site scripting (XSS)
attacks.

It's important to consider the security implications of where and how you store JWT
and make sure to use best practices to protect your users' data.

Q4 : Is it acceptable to store email addresses in database in string format?

Storing email addresses in a database in string format is acceptable and commonly


done practice. Email addresses are typically stored as strings in databases in order to
maintain their format and to ensure that they can be easily searched and sorted.

It's also important to make sure that the email addresses are stored in a way that is
consistent with the relevant regulations and guidelines such as General Data
Protection Regulation (GDPR) and Payment Card Industry Data Security Standard
(PCI DSS).

However, it's important to consider the security of the email addresses and take
appropriate measures to protect them. For example, it's a good practice to hash and
salt email addresses before storing them in a database, in order to protect them from
attackers who may gain access to the database.

Additionally, you should make sure that the email addresses are stored in a way that
complies with any relevant privacy regulations or guidelines. For example, GDPR
requires that personal data is collected and processed in a transparent and lawful
manner, and that it is only used for the purposes for which it was collected.

It's also important to consider the user's consent of the email address being stored,
and the need for it. In cases like unsubscribing or removing the email address from
the list, it should be easy and accessible for the user.

Q5 : Difference between spawn() and fork() methods in NodeJS?

The spawn() and fork() methods in [Link] are both used to create new child
processes, but they have some important differences.

The spawn() method creates a new process and returns a ChildProcess object, which
can be used to communicate with the child process using streams. It starts the new
process with a given command, and the child process inherits the environment
variables of the parent process. It is useful when you want to start a new process and
perform some I/O operations with it.

The fork() method also creates a new process and returns a ChildProcess object, but
it is specific to [Link]. It is used to spawn new [Link] processes and is similar to
spawn() but it allows passing the JavaScript file to be run in the new process as a
parameter, instead of a shell command. It also allows passing a message object to the
newly created process, which enables inter-process communication (IPC) between
the parent and the child process. This method is useful when you want to spawn a
new [Link] process and communicate with it using IPC.
In summary, spawn() method is used to create new process and run a command in it,
while the fork() method is used to create new [Link] process and run a JavaScript
file in it and also enables IPC between parent and child process.

Q6 : How would you implement a login and SignUp api in NodeJS and Express?

Implementing a login and signup API in [Link] and Express involves several steps,
including:

 Setting up a new Express project and installing the necessary dependencies


 Creating the routes and controllers for handling login and signup requests
 Connecting to a database to store and retrieve user information
 Implementing the logic for handling login and signup requests and validating
user input
 Securing the API by implementing authentication and authorization

Here is a basic example of how to implement a login and signup API in [Link] and
Express:

 Set up a new Express project and install the necessary dependencies, such as
express, body-parser, and mongoose (for connecting to MongoDB) using npm
 Create a new file called [Link] in the project's root directory. In this file,
import the express module and create two new routes for handling login and
signup requests.
const express = require("express");
const router = [Link]();

[Link]("/login", (req, res) => {


// login logic here
});

[Link]("/signup", (req, res) => {


// signup logic here
});

[Link] = router;

 In the main [Link] file, import the routes file and use it to handle login and
signup requests

const express = require("express");


const app = express();
const routes = require("./routes");

[Link]("/api", routes);
 Connect to a MongoDB database using mongoose and create a new model for
the User, that you will use to interact with the users collection.

const mongoose = require("mongoose");

[Link]("mongodb://localhost:27017/mydb", { useNewUrlParser: true });

const User = [Link]("User", {


email: String,
password: String
});

 In the login route, use the findOne method to find a user with a matching
email and password. If the user is found, set a session variable to indicate that
the user is logged in, and return a success message. If the user is not found,
return an error message.

[Link]("/login", (req, res) => {


[Link]({ email: [Link], password: [Link] }, (err, user)
=> {
if (err) {
[Link](500).send("Error finding user");
} else if (!user) {
[Link](404).send("Invalid email or password");
} else {
[Link] = user;
[Link]("Successfully logged in");
}
});
});

 In the signup route, use the create method to create a new user with the
provided email and password. If the user is successfully created, set a session
variable to indicate that the user is logged in, and return a success message. If
an error occurs, return an error message.

[Link]("/signup", (req, res) => {


[Link]({ email: [Link], password: [Link] },
(err, user) => {
if (err) {
[Link](500).send("Error creating user");
} else {
[Link] = user;
[Link]("Successfully signed up");
}
});
});
 Secure the API by implementing authentication and authorization. You can
use a library like [Link] to handle authentication and authorization. You
can set up passport to use strategies like JWT or OAuth for example.

const passport = require("passport");


[Link]([Link]());
require("./config/passport")(passport);

 Add protected routes that require authentication, by adding the


[Link] middleware to the routes.

[Link]("/profile", [Link]("jwt", { session: false }), (req, res) => {


[Link]([Link]);
});

Please note that this is a basic example and it is important to consider security and
scalability when building a production-ready API. This includes but not limited to:
password hashing, input validation, error handling, and more.

Q7 : How did you authenticate and authorize a user in your project?

Authentication is the process of verifying the identity of a user, while authorization is


the process of determining whether a user is allowed to access a certain resource or
perform a certain action.

There are several ways to authenticate and authorize users in a [Link] and Express
project, but some of the most popular methods include:

JWT (JSON Web Tokens): This is a common method for authenticating users in a
[Link] and Express project. JWT is a JSON object that is encoded and signed by the
server, and can be decoded and verified by the client. The server can include user
information in the JWT and send it to the client, which can then use the JWT to
authenticate the user on subsequent requests.

OAuth: This is an open standard for authorization that allows users to give third-
party access to their resources without sharing their passwords. This method is
commonly used in social media login.

[Link]: This is a popular authentication middleware for [Link] that supports


multiple strategies, including JWT and OAuth. [Link] simplifies the process of
handling authentication and authorization in a [Link] and Express project by
providing a consistent interface for different authentication strategies.

Cookies and sessions: This is the traditional way of handling authentication and
authorization in web applications. The server sends a session id to the client as a
cookie, and the client sends the session id back to the server on subsequent requests.
The server can then look up the session id and determine the identity of the user.
It's important to choose the right method of authentication and authorization for
your project, considering the security and scalability of the application and the user's
experience.
Q8 : How do we write plain html in express?

In Express, you can serve plain HTML files by using the sendFile() method, which is
provided by the [Link] middleware.

First, you need to make sure that the directory where your HTML files are located is
set up as a static directory. You can do this by using the [Link]() middleware
and specifying the directory where your HTML files are located.

Here is an example of how to set up a static directory and serve an HTML file in
Express:

const express = require("express");


const app = express();

[Link]([Link]("public"));

[Link]("/", (req, res) => {


[Link](__dirname + "/public/[Link]");
});

[Link](3000, () => {
[Link]("Server running on port 3000");
});

In this example, the public directory is set up as a static directory, and the [Link]
file is served when the root route is accessed.

You can also use the [Link]() method to serve any other HTML file located in
the static directory.

[Link]("/about", (req, res) => {


[Link](__dirname + "/public/[Link]");
});

It's worth noting that, if you have a lot of HTML files and want to avoid writing a
route for each one of them, you can use a template engine to generate the HTML on
the fly. Template engines like EJS, Handlebars or PUG are popular choices for this,
and they allow you to define reusable templates that can be populated with data from
your application.

Q9 : Write a program to call api from client architecture?

Here is an example of how to call an API from a client-side application using the
JavaScript fetch() method:

// Define the API endpoint


const API_URL = "[Link]

// Send a GET request to the API


fetch(API_URL)
.then(response => [Link]())
.then(data => {
// Handle the data received from the API
[Link](data);
})
.catch(error => {
// Handle any errors that occur
[Link](error);
});

This code sends a GET request to the API located at [Link] and
logs the data received from the API. The fetch() method returns a promise that
resolves with the API response, which can then be parsed as JSON using the json()
method.

You can also use the fetch() method to send other types of requests, such as POST,
PUT, and DELETE, by passing an options object as the second parameter to the
fetch() method, like this:

fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link]({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(res => [Link]())
.then(response => [Link]('Success:', [Link](response)))
.catch(error => [Link]('Error:', error));

In this example, I've added options for a POST request that sends a JSON object in
the body and sets the content-type to application/json. You can also include other
properties like credentials, mode, redirect, and referrer, depending on your use case.

It's worth noting that this is a basic example, in real-world applications, you should
consider security and error handling when making API requests, such as handling
different status codes, and validating the response. It's also good practice to use a
library such as Axios to make the requests, as it has better error handling, and it's
more robust.

Q10 : What is the use of multer?


Multer is a middleware for handling multipart/form-data, which is used for
uploading files. It is used to handle the files that are sent in the multipart/form-data
format in the HTTP requests, which is often used for uploading files. Multer provides
a way to handle these types of requests in an [Link] application.

It allows you to easily handle the files that are sent in the multipart/form-data format
by providing methods for handling the files and their metadata, such as file name,
size, and type. It also provides methods for handling the file upload process, such as
validating the files, renaming them, and storing them on the server.

Multer also provides a way to handle multiple files at once, and it can also manage
memory storage and disk storage.

In summary, Multer is a middleware used for handling file uploads in


[Link]/Express applications, it provides methods for handling the files and their
metadata, validating them, renaming them, and storing them on the server. It allows
for easy and efficient handling of file uploads in your application.

Q11 : How does body parser work?

The body-parser middleware is used to parse the incoming request bodies in a


[Link]/Express application. It allows you to access the request body as a JavaScript
object, making it easier to work with the data sent in the request.

When a client makes a request to the server, the request body is sent in the message
body of the request. The body-parser middleware parses this message body and
makes it available to the Express application as a JavaScript object. This makes it
easy to access and manipulate the data sent in the request, without having to
manually parse the request body as a string.

Body-parser supports different types of parsing, such as JSON, text and urlencoded.
The most common one is JSON parsing, which is used to parse JSON data and make
it available in the request body as a JavaScript object.

Here is an example of how to use the body-parser middleware to parse JSON data in
an Express application:

const express = require('express');


const bodyParser = require('body-parser');
const app = express();

[Link]([Link]());

[Link]('/', (req, res) => {


[Link]([Link]);
[Link]('Data received');
});

In this example, we are using the [Link]() method to parse JSON data sent
in the request body, and then we use the [Link] object to access the parsed data.
It's important to note that body-parser is not included in Express by default, it's a
separate module that needs to be installed and included in the application.
Additionally, body-parser is a middleware, therefore, it needs to be added to the
middleware stack in the application using [Link]([Link]()) for json
parsing.

Q12 : Explain this keyword with an example in NodeJS?

In JavaScript, the this keyword refers to the object that the current function is a
property of. The value of this can change depending on the context in which the
function is called.

In [Link], this typically refers to the current module, unless the function is called in
the context of an object.

Here is an example of how the this keyword works in a [Link] module:

// Define a variable on the module's exports


[Link] = "MyModule";

// Define a function on the module's exports


[Link] = function() {
[Link]([Link]);
};

// Call the function


printName(); // Outputs: MyModule

In this example, the this keyword inside the printName() function refers to the
current module, which is the exports object. Since we have assigned the value
"MyModule" to the name property of the exports object, the function logs
"MyModule" to the console.

It's worth noting that in a class, the this keyword refers to the current instance of the
class, and it's different from this in a module.

class MyClass {
constructor(name) {
[Link] = name;
}

printName() {
[Link]([Link]);
}
}

const myClass = new MyClass("MyClass");


[Link](); // Outputs: "MyClass"

In this example, the this keyword inside the printName() function refers to the
current module, which is the exports object. Since we have assigned the value
"MyModule" to the name property of the exports object, the function logs
"MyModule" to the console.

It's worth noting that in a class, the this keyword refers to the current instance of the
class, and it's different from this in a module.

class MyClass {
constructor(name) {
[Link] = name;
}

printName() {
[Link]([Link]);
}
}

const myClass = new MyClass("MyClass");


[Link](); // Outputs: "MyClass"

In this example, the this keyword inside the printName() function refers to the
current instance of the MyClass class, which is the myClass object.

It's important to note that the behavior of this can be affected by how a function is
called, and by the use of bind, call or apply methods, and also by the use of arrow
functions.

Q13 : Have you created any API? How did you add your data to API?

There are several ways to add data to an API, depending on the type of data and the
architecture of the API. Here are a few common methods:

POST requests: One of the most common methods of adding data to an API is by
sending a POST request to a specific endpoint. The request body should contain the
data to be added, and the server will typically parse the request body, validate the
data, and then insert the data into the database.

PUT requests: Another method of adding data to an API is by sending a PUT request
to a specific endpoint. This method is used for updating existing data. Just like POST
request, the request body should contain the data to be added, and the server will
typically parse the request body, validate the data, and then update the data in the
database.

Database seeders: Another method of adding data to an API is by using database


seeders. Database seeders are scripts that are run once to insert a set of data into the
database. This is a useful method when you want to add a large amount of data to the
API at once.

Importing data: Some APIs allow data to be imported in bulk by providing an import
endpoint or a bulk insert method. This is useful when you have a lot of data in a file
and want to insert it all at once.
It's important to note that when adding data to an API, you should consider security,
validation and data integrity. It's also important to implement error handling to
return appropriate error messages to the client in case of any issues.

Q14 : What is difference between restapi and graph ql?

REST (Representational State Transfer) and GraphQL are both ways of building APIs
(Application Programming Interfaces), but they have some key differences:

Endpoint structure: REST APIs have a fixed structure of endpoints, where each
endpoint represents a specific resource or collection of resources. In contrast,
GraphQL has a single endpoint that handles all queries, and the client can specify
exactly what data it needs in the query.

Data retrieval: In REST APIs, the client needs to make multiple requests to different
endpoints to retrieve all the necessary data. With GraphQL, the client can retrieve all
the necessary data in a single request by specifying exactly what data is needed in the
query.

Data structure: REST APIs typically return a fixed structure of data, determined by
the endpoint that was called. With GraphQL, the client can specify the exact shape of
the data it needs, which means the server does not have to return unnecessary data.

Flexibility: REST APIs have a fixed structure, which means that adding new data or
changing the structure of the data can be difficult and may require changes to
multiple endpoints. GraphQL provides more flexibility in terms of querying data and
allows for real-time updates, which makes it easier to add new data or update the
structure of the data.

Security: REST APIs are generally easier to secure than GraphQL, because the
endpoints are fixed and the

Q15 : Explain how you would implement logout feature in your project?

Implementing a logout feature in a project involves several steps, here is a general


overview of how it can be done:

Invalidating the session: When a user logs out, the server should invalidate the user's
session. This can be done by destroying the session on the server-side, and clearing
any session data stored on the client-side (such as in a browser cookie).

Removing the authentication token: When a user logs out, the server should also
remove any authentication tokens associated with the user. This can be done by
storing the tokens in a database and removing the token when the user logs out.

Clearing the client-side state: The client-side application should also be notified of
the logout and should clear any data or state associated with the authenticated user.
This can be done by removing any data from the client-side storage, such as
localStorage or browser cookies, and redirecting the user to the login page
Redirecting the user: After the user logs out, the client-side application should
redirect the user to the login page or a landing page.

Here is a sample implementation of a logout route in an express application

[Link]('/logout', (req, res) => {


[Link]();
[Link]('token');
[Link]('/login');
});

In this example, the logout route is handled by the /logout endpoint, which destroys
the session, clears the token cookie, and redirects the user to the login page.

It's important to note that the implementation of logout feature may vary depending
on the authentication mechanism used in the project. It's also important to consider
the security of the logout feature and to ensure that it is properly implemented to
prevent any security issues.

Also, it's good practice to implement some form of server-side validation to ensure
that the logout request is valid, for example, by checking if the user is already logged
out or if the session is already expired.

You should also pay attention to the browser behavior when you logout, for example,
by clearing the browser cache, session storage, local storage or cookies.

In addition, you should consider the user experience when logging out, for example,
by providing clear feedback to the user that they have been logged out, and by giving
them the option to log in again.

In summary, implementing a logout feature in a project involves invalidating the


session, removing the authentication token, clearing the client-side state and
redirecting the user to the login page or a landing page. It's important to consider the
security and user experience when implementing the feature.

Q16 : What is Database? Difference between MongoDB and SQL?

A database is a collection of data that is stored and organized in a way that allows for
efficient retrieval, insertion, and manipulation of the data. There are different types
of databases, such as relational databases and non-relational databases.

MongoDB and SQL are two different types of databases.

MongoDB: MongoDB is a NoSQL, or non-relational, database. It stores data in a


format called BSON (Binary JSON), which is similar to JSON. MongoDB is known
for its flexibility and scalability, and it's often used for storing large amounts of
unstructured data. MongoDB is also a document-oriented database, which means it
stores data in documents (or objects) rather than in tables with rows and columns.
SQL: SQL (Structured Query Language) is a relational database. It stores data in
tables with rows and columns, and it uses a declarative language to define and
manipulate the data. SQL is known for its consistency and reliability, and it's often
used for storing structured data.

The main difference between MongoDB and SQL is the data model, MongoDB uses a
document-based data model and SQL uses a table-based data model. MongoDB is
more flexible and scalable but it's less consistent and reliable when compared to SQL.
MongoDB is also more efficient when dealing with large amounts of unstructured
data and SQL is better at handling structured data.

It's worth noting that MongoDB is a relatively new technology compared to SQL
which is an older technology, but both are widely used in different use cases and both
have their own strengths and weaknesses.

Q17 : What is Normalisation and its types?

Normalization is the process of organizing data in a database so that it meets certain


rules and criteria, called normal forms. The main goal of normalization is to
minimize data redundancy and improve data integrity by eliminating data
anomalies.

There are several normal forms, each with a different level of normalization. The
most commonly used normal forms are:

First Normal Form (1NF): This is the most basic form of normalization, it requires
that each table has a primary key and that each field contains only atomic
(indivisible) values. This means that all repeating groups should be removed and
placed in a separate table.

Second Normal Form (2NF): A table is in 2NF if it is already in 1NF and all non-
primary key fields are dependent on the primary key. This means that each non-
primary key field should depend on the entire primary key, and not just a part of it.

Third Normal Form (3NF): A table is in 3NF if it is already in 2NF and there are no
transitive dependencies. This means that all non-primary key fields should depend
only on the primary key and not on any other non-primary key field.

Boyce-Codd Normal Form (BCNF): A table is in BCNF if it is already in 3NF and all
determinants are candidate keys.

Fourth Normal Form (4NF): A table is in 4NF if it is already in BCNF and there are
no multi-valued dependencies.

Fifth Normal Form (5NF): A table is in 5NF if it is already in 4NF and there are no
cyclic dependencies.

It's worth noting that normalization is a multi-step process and it's not always
necessary to normalize a database to the highest normal form. In some cases, it may
be more beneficial to denormalize the data for performance reasons.
Q18 : What is ORM?

ORM stands for Object-Relational Mapping. It is a technique that allows a


programmer to interact with a database using an object-oriented programming
language, rather than writing raw SQL queries.

An ORM library maps the objects in the programming language to the rows and
columns of the database, and provides an API for performing CRUD (Create, Read,
Update and Delete) operations on the data. It also abstracts away the underlying
database, so that the same code can work with different databases, as long as the
ORM library supports them.

The main advantage of using an ORM is that it allows the developer to work with the
data in an object-oriented way, which is more natural and easier to understand than
working with raw SQL queries. It also helps to prevent SQL injection attacks by
automatically escaping user input.

There are several popular ORM libraries available for different programming
languages, such as Hibernate (Java), ActiveRecord (Ruby on Rails) and Eloquent
(Laravel/PHP).

It's worth noting that ORM can have a performance overhead when working with
large data sets and complex queries, but with proper use and understanding of ORM,
it can make the development process faster and more efficient.

Q19 : What is the benefit of using mongoose over mongoDB ?

Mongoose is an Object Document Mapping (ODM) library for MongoDB and


[Link]. It provides an API for interacting with MongoDB in a more organized and
structured way, and it offers several benefits over using MongoDB directly:

Schema validation: Mongoose allows you to define a schema for your data, which can
be used to validate the data before it is saved to the database. This helps to ensure
that the data is valid and conforms to a specific structure.

Query building: Mongoose provides a powerful query builder API for constructing
complex queries. This makes it easier to work with the data, and it can help to
prevent SQL injection attacks.

Middleware: Mongoose supports middleware, which allows you to run certain code
before or after certain events, such as saving or finding data. This can be used to
perform additional actions, such as logging or auditing.

Type casting: Mongoose automatically casts data types to the correct types, so that
you don't have to worry about converting strings to numbers or dates.

Plugins: Mongoose has a plugin system that allows you to add additional
functionality to the ORM. There are many plugins available that can be used to add
features such as pagination, password hashing, and more.
Models: Mongoose provides a model layer on top of MongoDB, which allows you to
create classes that correspond to collections in MongoDB, and have methods that
correspond to CRUD operations.
mongodb
In summary, Mongoose provides a higher-level abstraction over MongoDB and
allows you to work with the data in a more organized and structured way. It offers
features such as schema validation, query building, middleware, type casting,
plugins, and models, which can make the development process faster and more
efficient. Additionally, it also provides security benefits, such as preventing SQL
injection attacks.

Q20 : Write and explain some commonly used queries?

MongoDB uses a query language that is similar to JSON, called the MongoDB query
language. Here are some commonly used MongoDB queries and a brief explanation
of what they do:

 Find: This query is used to retrieve documents from a collection. The syntax is
[Link]({query criteria}). For example, [Link]({age: 30})
would find all documents in the "users" collection where the "age" field is
equal to 30.

 Insert: This query is used to insert a new document into a collection. The
syntax is [Link]({document}). For example,
[Link]({name: "John", age: 30}) would insert a new document into
the "users" collection with the fields "name" and "age".

 Update: This query is used to update existing documents in a collection. The


syntax is [Link]({query criteria}, {update data}, {options}). For
example, [Link]({name: "John"}, {$set: {age: 35}}) would update all
documents in the "users" collection where the "name" field is equal to "John"
and set the "age" field to 35.

 Delete: This query is used to delete documents from a collection. The syntax is
[Link]({query criteria}, {justOne: true/false}). For example,
[Link]({name: "John"}) would delete all documents in the "users"
collection where the "name" field is equal to "John".

You might also like