TCS Interview preparation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

C++ Interview ques ons: h ps://www.geeksforgeeks.

org/cpp-interview-ques ons/
Java Interview ques ons: h ps://www.geeksforgeeks.org/java-interview-ques ons/

JAVASCRIPT INTERVIEW QUESTIONS


1. What are the differences between Java and JavaScript?
JavaScript is a client-side scrip ng language and Java is object Oriented Programming language. Both
of them are totally different from each other.
 JavaScript: It is a light-weighted programming language (“scrip ng language”) for developing
interac ve web pages. It can insert dynamic text into the HTML elements. JavaScript is also
known as the browser’s language.
 Java: Java is one of the most popular programming languages. It is an object-oriented
programming language and has a virtual machine pla orm that allows you to create
compiled programs that run on nearly every pla orm. Java promised, “Write Once, Run
Anywhere”.
2. What are JavaScript Data Types?
There are three major Data types in JavaScript.
 Primi ve
o Numbers
o Strings
o Boolean
o Symbol
 Trivial
o Undefined
o Null
 Composite
o Objects
o Func ons
o Arrays
3. Which symbol is used for comments in JavaScript?
Comments prevent the execu on of statements. Comments are ignored while the compiler executes
the code. There are two type of symbols to represent comments in JavaScript:
 Double slash: It is known as a single-line comment.
// Single line comment

 Slash with Asterisk: It is known as a mul -line comment.


/*
Mul -line comments
...
*/

4. What would be the result of 3+2+”7″?


Here, 3 and 2 behave like an integer, and “7” behaves like a string. So 3 plus 2 will be 5. Then the
output will be 5+”7″ = 57.
5. What is the use of the isNaN func on?
The number isNan func on determines whether the passed value is NaN (Not a number) and is of
the type “Number”. In JavaScript, the value NaN is considered a type of number. It returns true if the
argument is not a number, else it returns false.
6. Which is faster in JavaScript and ASP script?
JavaScript is faster compared to ASP Script. JavaScript is a client-side scrip ng language and does not
depend on the server to execute. The ASP script is a server-side scrip ng language always
dependable on the server.
7. What is nega ve infinity?
The nega ve infinity is a constant value represents the lowest available value. It means that no other
number is lesser than this value. It can be generate using a self-made func on or by an arithme c
opera on. JavaScript shows the NEGATIVE_INFINITY value as -Infinity.
8. Is it possible to break JavaScript Code into several lines?
Yes, it is possible to break the JavaScript code into several lines in a string statement. It can be
broken by using the backslash ‘\’.
For example:
document.write("A Online Computer Science Portal\ for Geeks")
The code-breaking line is avoid by JavaScript which is not preferable.
let gfg= 10, GFG = 5,
Geeks =
gfg + GFG;
9. Which company developed JavaScript?
Netscape developed JavaScript and was created by Brenden Eich in the year of 1995.
10. What are undeclared and undefined variables?
 Undefined: It occurs when a variable is declare not not assign any value. Undefined is not a
keyword.
 Undeclared: It occurs when we try to access any variable which is not ini alize or declare
earlier using the var or const keyword. If we use ‘typeof’ operator to get the value of an
undeclare variable, we will face the run me error with the return value as “undefined”. The
scope of the undeclare variables is always global.
11. Write a JavaScript code for adding new elements dynamically.
html
<!DOCTYPE html>
<html lang="en">
<head>
< tle>Document</ tle>
</head>

<body>
<bu on onclick="create()">
Click Here!
</bu on>

<script>
func on create() {
let geeks = document.createElement('geeks');
geeks.textContent = "Geeksforgeeks";
geeks.setA ribute('class', 'note');
document.body.appendChild(geeks);
}
</script>
</body>
</html>
12. What are global variables? How are these variables declared, and what are the problems
associated with them?
In contrast, global variables are the variables that define outside of func ons. These variables have a
global scope, so they can be used by any func on without passing them to the func on as
parameters.
Example:
javascript
let petName = "Rocky"; //Global Variable
myFunc on();

func on myFunc on() {


document.getElementById("geeks").innerHTML
= typeof petName + "- " +
"My pet name is " + petName;
}

document.getElementById("Geeks")
.innerHTML = typeof petName + "- " +
"My pet name is " + petName;
It is difficult to debug and test the code that relies on global variables.
13. What do you mean by NULL in JavaScript?
The NULL value represents that no value or no object. It is known as empty value/object.
14. How to delete property-specific values?
The delete keyword deletes the whole property and all the values at once like
let gfg={Course: "DSA", Dura on:30};
delete gfg.Course;
15. What is a prompt box?
The prompt box is a dialog box with an op onal message promp ng the user to input some text. It is
o en used if the user wants to input a value before entering a page. It returns a string containing the
text entered by the user, or null.
16. What is the ‘this’ keyword in JavaScript?
Func ons in JavaScript are essen al objects. Like objects, it can be assign to variables, pass to other
func ons, and return from func ons. And much like objects, they have their own proper es. ‘this’
stores the current execu on context of the JavaScript program. Thus, when it use inside a func on,
the value of ‘this’ will change depending on how the func on is defined, how it is invoked, and the
default execu on context.
17. Explain the working of mers in JavaScript. Also elucidate the drawbacks of using the mer, if
any.
The mer executes some specific code at a specific me or any small amount of code in repe on to
do that you need to use the func ons setTimout, setInterval, and clearInterval. If the JavaScript
code sets the mer to 2 minutes and when the mes are up then the page displays an alert message
“ mes up”. The setTimeout() method calls a func on or evaluates an expression a er a specified
number of milliseconds.
18. What is the difference between ViewState and SessionState?
 ViewState: It is specific to a single page in a session.
 SessionState: It is user specific that can access all the data on the web pages.
19. How to submit a form using JavaScript?
You can use document.form[0].submit() method to submit the form in JavaScript.
20. Does JavaScript support automa c type conversion?
Yes, JavaScript supports automa c type conversion.
JavaScript Intermediate Interview Ques ons
21. What are all the looping structures in JavaScript ?
 while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condi on. The while loop can be thought of as a
repea ng if statement.
 for loop: A for loop provides a concise way of wri ng the loop structure. Unlike a while loop,
for statement consumes the ini aliza on, condi on and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
 do while: A do-while loop is similar to while loop with the only difference that it checks the
condi on a er execu ng the statements, and therefore is an example of Exit Control Loop.
22. How can the style/class of an element be changed?
To change the style/class of an element there are two possible ways. We
use document.getElementByID method
document.getElementById("myText").style.fontSize = "16px;
document.getElementById("myText").className = "class";
23. Explain how to read and write a file using JavaScript?
 The readFile() func ons is used for reading opera on.
readFile( Path, Op ons, Callback)
 The writeFile() func ons is used for wri ng opera on.
writeFile( Path, Data, Callback)
24. What is called Variable typing in JavaScript ?
The variable typing is the type of variable used to store a number and using that same variable to
assign a “string”.
Geeks = 42;
Geeks = "GeeksforGeeks";
25. How to convert the string of any base to integer in JavaScript?
In JavaScript, parseInt() func on is used to convert the string to an integer. This func on returns an
integer of base which is specified in second argument of parseInt() func on. The parseInt() func on
returns Nan (not a number) when the string doesn’t contain number.
26. Explain how to detect the opera ng system on the client machine?
To detect the opera ng system on the client machine, one can simply use navigator.appVersion or
navigator.userAgent property. The Navigator appVersion property is a read-only property and it
returns the string that represents the version informa on of the browser.
27. What are the types of Pop up boxes available in JavaScript?
There are three types of pop boxes available in JavaScript.
 Alert
 Confirm
 Prompt
28. What is the difference between an alert box and a confirma on box?
An alert box will display only one bu on which is the OK bu on. It is used to inform the user about
the agreement has to agree. But a Confirma on box displays two bu ons OK and cancel, where the
user can decide to agree or not.
29. What is the disadvantage of using innerHTML in JavaScript?
There are lots of disadvantages of using the innerHTML in JavaScript as the content will replace
everywhere. If you use += like “innerHTML = innerHTML + ‘html’” s ll the old content is replaced by
HTML. It preserves event handlers a ached to any DOM elements.
30. What is the use of void(0) ?
The void(0) is used to call another method without refreshing the page during the calling me
parameter “zero” will be passed.
For further reading, check out our dedicated ar cle on Intermediate Javascript Interview Ques ons.
Inside, you’ll discover over 20 ques ons with detailed answers.
JavaScript Interview Ques ons for Experienced
31. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program or a func on in a
“strict” opera ng context. This strict context prevents certain ac ons from being taken and throws
more excep ons. The statement “use strict” instructs the browser to use the Strict mode, which is a
reduced and safer feature set of JavaScript.
32. How to get the status of a CheckBox?
The DOM Input Checkbox Property is used to set or return the checked status of a checkbox field.
This property is used to reflect the HTML Checked a ribute.
document.getElementById("GFG").checked;
If the CheckBox is checked then it returns True.
33. How to explain closures in JavaScript and when to use it?
The closure is created when a child func ons to keep the environment of the parent’s scope even
a er the parent’s func on has already executed. The Closure is a locally declared variable related to
a func on. The closure will provide be er control over the code when using them.
Javascript
// Explana on of closure
func on foo() {
let b = 1;
func on inner() {
return b;
}
return inner;
}
let get_func_inner = foo();

console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
34. What is the difference between call() and apply() methods ?
Both methods are used in a different situa on
 call() Method: It calls the method, taking the owner object as argument. The keyword this
refers to the ‘owner’ of the func on or the object it belongs to. We can call a method that
can be used on different objects.
 apply() Method: The apply() method is used to write methods, which can be used on
different objects. It is different from the func on call() because it takes arguments as an
array.
35. How to target a par cular frame from a hyperlink in JavaScript ?
This can be done by using the target a ribute in the hyperlink. Like
<a href="/geeksforgeeks.htm" target="newframe">New Page</a>
36. Write the errors shown in JavaScript?
There are three different types of errors in JavaScript.
 Syntax error: A syntax error is an error in the syntax of a sequence of characters or tokens
that are intended to be wri en in a par cular programming language.
 Logical error: It is the most difficult error to be traced as it is the error on the logical part of
the coding or logical error is a bug in a program that causes to operate incorrectly and
terminate abnormally.
 Run me Error: A run me error is an error that occurs during the running of the program,
also known as an excep on.
37. What is the difference between JavaScript and Jscript?
JavaScript
 It is a scrip ng language developed by Netscape.
 It is used to design client and server-side applica ons.
 It is completely independent of Java language.
Jscript
 It is a scrip ng language developed by Microso .
 It is used to design ac ve online content for the word wide Web.
38. What does var myArray = [[]]; statement declares?
In JavaScript, this statement is used to declare a two-dimensional array.
39. How many ways an HTML element can be accessed in JavaScript code?
There are four possible ways to access HTML elements in JavaScript which are:
 getElementById() Method: It is used to get the element by its id name.
 getElementsByClass() Method: It is used to get all the elements that have the given
classname.
 getElementsByTagName() Method: It is used to get all the elements that have the given tag
name.
 querySelector() Method: This func on takes CSS style selector and returns the first selected
element.
40. What is the difference between innerHTML & innerText?
The innerText property sets or returns the text content as plain text of the specified node, and all its
descendants whereas the innerHTML property sets or returns the plain text or HTML contents in the
elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesn’t automa cally
encode and decode text.
41. What is an event bubbling in JavaScript?
Consider a situa on an element is present inside another element and both of them handle an
event. When an event occurs in bubbling, the innermost element handles the event first, then the
outer, and so on.
JavaScript Interview Questions and Answers
(2024) – Intermediate Level
1. What are all the looping structures in JavaScript ?

 while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condi on. The while loop can be thought of as a
repea ng if statement.

 for loop: A for loop provides a concise way of wri ng the loop structure. Unlike a while loop,
for statement consumes the ini aliza on, condi on and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.

 do while: A do-while loop is similar to while loop with the only difference that it checks the
condi on a er execu ng the statements, and therefore is an example of Exit Control Loop.

2. How can the style/class of an element be changed?

To change the style/class of an element there are two possible ways. We


use document.getElementByID method

document.getElementById("myText").style.fontSize = "16px;

document.getElementById("myText").className = "class";

3. Explain how to read and write a file using JavaScript?

 The readFile() func ons is used for reading opera on.

readFile( Path, Op ons, Callback)

 The writeFile() func ons is used for wri ng opera on.

writeFile( Path, Data, Callback)

4. What is called Variable typing in JavaScript ?

The variable typing is the type of variable used to store a number and using that same variable to
assign a “string”.

Geeks = 42;

Geeks = "GeeksforGeeks";

5. How to convert the string of any base to integer in JavaScript?

In JavaScript, parseInt() func on is used to convert the string to an integer. This func on returns an
integer of base which is specified in second argument of parseInt() func on. The parseInt() func on
returns Nan (not a number) when the string doesn’t contain number.

6. Explain how to detect the opera ng system on the client machine?


To detect the opera ng system on the client machine, one can simply use navigator.appVersion or
navigator.userAgent property. The Navigator appVersion property is a read-only property and it
returns the string that represents the version informa on of the browser.

7. What are the types of Pop up boxes available in JavaScript?

There are three types of pop boxes available in JavaScript.

 Alert

 Confirm

 Prompt

8. What is the difference between an alert box and a confirma on box?

An alert box will display only one bu on which is the OK bu on. It is used to inform the user about
the agreement has to agree. But a Confirma on box displays two bu ons OK and cancel, where the
user can decide to agree or not.

9. What is the disadvantage of using innerHTML in JavaScript?

There are lots of disadvantages of using the innerHTML in JavaScript as the content will replace
everywhere. If you use += like “innerHTML = innerHTML + ‘html'” s ll the old content is replaced by
HTML. It preserves event handlers a ached to any DOM elements.

10. What is the use of void(0) ?

The void(0) is used to call another method without refreshing the page during the calling me
parameter “zero” will be passed.

11. What are JavaScript Cookies ?

Cookies are small files that are stored on a user’s computer. They are used to hold a modest amount
of data specific to a par cular client and website and can be accessed either by the web server or by
the client’s computer. When cookies were invented, they were basically li le documents containing
informa on about you and your preferences. For instance, when you select the language in which
you want to view your website, the website would save the informa on in a document called a
cookie on your computer, and the next me when you visit the website, it would be able to read a
cookie saved earlier.

12. How to create a cookie using JavaScript?

To create a cookie by using JavaScript you just need to assign a string value to the document.cookie
object.

document.cookie = "key1 = value1; key2 = value2; expires = date";

13. How to read a cookie using JavaScript?

The value of the document.cookie is used to create a cookie. Whenever you want to access the
cookie you can use the string. The document.cookie string keep a list of name = value pairs
separated by semicolons, where name is the name of a cookie and the value is its string value.

14. How to delete a cookie using JavaScript?


Dele ng a cookie is much easier than crea ng or reading a cookie, you just need to set the expires =
“past me” and make sure one thing defines the right cookie path unless few will not allow you to
delete the cookie.

15. What are escape characters and escape() func on?

 Escape character: This character is required when you want to work with some special
characters like single and double quotes, apostrophes, and ampersands. All the special
character plays an important role in JavaScript, to ignore that or to print that special
character, you can use the escape character backslash “\”. It will normally ignore and behave
like a normal character.

// Need escape character

document.write("GeeksforGeeks: A Computer Science Portal "for Geeks" ")

document.write("GeeksforGeeks: A Computer Science Portal \"for Geeks\" ")

 escape() func on: The escape() func on takes a string as a parameter and encodes it so that
it can be transmi ed to any computer in any network which supports ASCII characters.

16. Whether JavaScript has a concept-level scope?

JavaScript is not concept-level scope, the variables declared inside any func on have scope inside the
func on.

17. How generic objects can be created in JavaScript?

To create a generic object in JavaScript use:

var I = new object();

18. Which keywords are used to handle excep ons?

When execu ng JavaScript code, errors will almost definitely occur. These errors can occur due to the
fault from the programmer’s side due to the wrong input or even if there is a problem with the logic
of the program. But all errors can be solved by using the below commands.

 The try statement lets you test a block of code to check for errors.

 The catch statement lets you handle the error if any are present.

 The throw statement lets you make your own errors.

19. What is the use of the blur func on?

It is used to remove focus from the selected element. This method starts the blur event or it can be
a ached to a func on to run when a blur event occurs.

20. What is the unshi method in JavaScript?

It is used to insert elements in the front of an array. It is like a push method that inserts elements at
the beginning of the array.
JavaScript Interview Questions and Answers
(2024) – Advanced Level

1. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program or a func on in a
“strict” opera ng context. This strict context prevents certain ac ons from being taken and throws
more excep ons. The statement “use strict” instructs the browser to use the Strict mode, which is a
reduced and safer feature set of JavaScript.

2. How to get the status of a CheckBox?

The DOM Input Checkbox Property is used to set or return the checked status of a checkbox field.
This property is used to reflect the HTML Checked a ribute.

document.getElementById("GFG").checked;

If the CheckBox is checked then it returns True.

3. How to explain closures in JavaScript and when to use it?

The closure is created when a child func ons to keep the environment of the parent’s scope even
a er the parent’s func on has already executed. The Closure is a locally declared variable related to
a func on. The closure will provide be er control over the code when using them.

 javascript

// Explana on of closure

func on foo() {

let b = 1;

func on inner() {

return b;

return inner;

let get_func_inner = foo();

console.log(get_func_inner());

console.log(get_func_inner());

console.log(get_func_inner());

4. What is the difference between call() and apply() methods ?


Both methods are used in a different situa on

 call() Method: It calls the method, taking the owner object as argument. The keyword this
refers to the ‘owner’ of the func on or the object it belongs to. We can call a method that
can be used on different objects.

 apply() Method: The apply() method is used to write methods, which can be used on
different objects. It is different from the func on call() because it takes arguments as an
array.

5. How to target a par cular frame from a hyperlink in JavaScript ?

This can be done by using the target a ribute in the hyperlink. Like

<a href="/geeksforgeeks.htm" target="newframe">New Page</a>

6. Write the errors shown in JavaScript?

There are three different types of errors in JavaScript.

 Syntax error: A syntax error is an error in the syntax of a sequence of characters or tokens
that are intended to be wri en in a par cular programming language.

 Logical error: It is the most difficult error to be traced as it is the error on the logical part of
the coding or logical error is a bug in a program that causes to operate incorrectly and
terminate abnormally.

 Run me Error: A run me error is an error that occurs during the running of the program,
also known as an excep on.

7. What is the difference between JavaScript and Jscript?

JavaScript

 It is a scrip ng language developed by Netscape.

 It is used to design client and server-side applica ons.

 It is completely independent of Java language.

Jscript

 It is a scrip ng language developed by Microso .

 It is used to design ac ve online content for the world wide Web.

8. What does var myArray = [[]]; statement declares?

In JavaScript, this statement is used to declare a two-dimensional array.

9. How many ways an HTML element can be accessed in JavaScript code?

There are four possible ways to access HTML elements in JavaScript which are:

 getElementById() Method: It is used to get the element by its id name.

 getElementsByClass() Method: It is used to get all the elements that have the given
classname.
 getElementsByTagName() Method: It is used to get all the elements that have the given tag
name.

 querySelector() Method: This func on takes CSS style selector and returns the first selected
element.

10. What is the difference between innerHTML & innerText?

The innerText property sets or returns the text content as plain text of the specified node, and all its
descendants whereas the innerHTML property sets or returns the plain text or HTML contents in the
elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesn’t automa cally
encode and decode text.

11. What is an event bubbling in JavaScript?

Consider a situa on an element is present inside another element and both of them handle an
event. When an event occurs in bubbling, the innermost element handles the event first, then the
outer, and so on.

12. What will be the output of the following code?

 javascript

let X = { geeks: 1 };

let Output = (func on () {

delete X.geeks;

return X.geeks;

})();

console.log(output);

Here the delete will delete the property of the object. X is the object with the geek’s property and it
is a self-invoking func on that will delete the geek’s property from object X so the result will be
undefined.

13. How are JavaScript and ECMA Script related?

JavaScript is the main language that has to maintain some rules and regula ons which is ECMA
Script, these rules also bring new features for the language JavaScript.

14. How to hide JavaScript code from old browsers that don’t support JavaScript?

To hide the JavaScript codes from the old browsers that don’t support JavaScript you can use

<!-- before <script> tag and another //--> a er </script> tag

all the old browsers that will take that as a long comment of HTML. New browsers that support
JavaScript will take that as an online comment.

15. What will be the output of the following code?


let output = (func on(x) {

delete x;

return x;

})(0);

document.write(output);

The output will be 0. The delete operator is used to delete the operator of the object but the X is not
the object here it is a local variable. The delete operator doesn’t affect local variables.

16. In JavaScript, answer if the following expressions result in true or false.

"0" == 0 // true or false ?

"" == 0 // true or false ?

"" == "0" // true or false ?

The result will be True for 1st and 2nd case and False for the 3rd case.

17. How to use any browser for debugging?

By pressing the F12 we can trigger the debugging mode of any browser and can view the result by
taping the console.

18. What is javascript Hois ng?

When any interpreter runs the code then all the variables are re-hoisted to the top of the original
scope. This method is applicable for declara on not for the ini aliza on of a variable. This is known
as a javascript Hois ng.

19. What is the syntax of ‘Self Invoking Func on’ ?

The syntax for Self-Invoking Func on: The last bracket contains the func on expression.

(func on () {

return // body of the func on

}());

20. How to use external JavaScript file in another JavaScript file?

You can use the below code to use external JavaScript code in another JavaScript file.

 javascript

let script = document.createElement('script');

script.src = "external javascript file";

document.head.appendChild(script)
MongoDB Basic Interview ques ons:
1. How does MongoDB differ from tradi onal rela onal databases?
 MongoDB is a NoSQL database, while tradi onal rela onal databases are SQL-based.
 It stores data in flexible, schema-less documents, whereas rela onal databases use
structured tables with fixed schemas.
 It is designed for horizontal scalability and can handle large volumes of data, while rela onal
databases typically scale ver cally.
2. Can you explain what a document in MongoDB is?
A document is a JSON-like data structure that stores and represents data. It can contain key-value
pairs, arrays, and nested documents. Documents are stored in collec ons, equivalent to tables in
rela onal databases.
3. What is a collec on in MongoDB?
A collec on in MongoDB is a grouping of documents. Collec ons are schema-less, meaning
documents in the same collec on can have different structures. Collec ons are similar to tables in
tradi onal rela onal databases.

What Is MongoDB?
MongoDB is a popular open-source, NoSQL (non-rela onal) database management system that is
created to store, retrieve, and manage data flexibly and scalable. MongoDB is classified as a
document database, storing data in a format similar to JSON (JavaScript Object Nota on)
documents.
1. Document-Oriented: MongoDB stores data in collec ons that contain documents. Each
document is a JSON-like object, and these documents can have varying structures within the
same collec on. This flexibility makes it well-suited for handling data with dynamic or
evolving schemas.
2. Schema-less: Unlike tradi onal rela onal databases, MongoDB doesn't require a predefined
schema for data. You can insert documents with different fields in the same collec on
without altering the schema.
3. Scalability: MongoDB is designed for horizontal scalability. You can distribute data across
mul ple servers and clusters to handle large volumes of data and high traffic loads.
4. High Performance: MongoDB can provide high read and write throughput, especially for
certain types of applica ons where rapid data access is cri cal.
5. Rich Query Language: MongoDB supports a powerful query language for retrieving and
manipula ng data. You can perform complex queries, indexing, and aggrega on opera ons.
6. Geospa al Data: MongoDB has built-in support for geospa al data and allows you to
perform geospa al queries, making it suitable for loca on-based applica ons.
7. Replica on and High Availability: MongoDB supports replica on for data redundancy and
high availability. It can automa cally recover from hardware failures and provide con nuous
service.
8. Flexible Indexing: You can create custom indexes to op mize query performance for specific
use cases.
9. Community and Enterprise Edi ons: MongoDB provides a freely available Community Edi on
and a premium Enterprise Edi on, which includes extra func onali es and comprehensive
support.
10. Large Ecosystem: MongoDB boasts a thriving and engaged community, comprehensive
documenta on, and diverse drivers and connectors tailored to numerous programming
languages and frameworks.
MongoDB is commonly used in web and mobile applica ons, content management systems, real-
me analy cs, and other scenarios where flexibility, scalability, and speed are essen al. It's a popular
choice for developers and organiza ons looking to work with data that doesn't fit neatly into
tradi onal rela onal databases. Now, let’s look at the most popular MongoDB Interview Ques ons
and Answers for 2024.
MongoDB Basic Interview Ques ons
1. How does MongoDB differ from tradi onal rela onal databases?
 MongoDB is a NoSQL database, while tradi onal rela onal databases are SQL-based.
 It stores data in flexible, schema-less documents, whereas rela onal databases use
structured tables with fixed schemas.
 It is designed for horizontal scalability and can handle large volumes of data, while rela onal
databases typically scale ver cally.
2. Can you explain what a document in MongoDB is?
A document is a JSON-like data structure that stores and represents data. It can contain key-value
pairs, arrays, and nested documents. Documents are stored in collec ons, equivalent to tables in
rela onal databases.
3. What is a collec on in MongoDB?
A collec on in MongoDB is a grouping of documents. Collec ons are schema-less, meaning
documents in the same collec on can have different structures. Collec ons are similar to tables in
tradi onal rela onal databases.
4. How does MongoDB store data?
MongoDB stores data in BSON (Binary JSON) format, a binary-encoded serializa on of JSON-like
documents. These documents are stored in collec ons within databases.
5. What is a primary key in MongoDB?
In MongoDB, the `_id` field serves as the primary key for a document. It must be unique within a
collec on and is automa cally generated if not provided during document inser on.
6. Can you explain the concept of sharding in MongoDB?
Sharding in MongoDB is a strategy used to distribute data horizontally across numerous servers or
clusters, efficiently managing extensive datasets and heavy workloads. In this approach, data is
divided into dis nct subsets known as shards, and MongoDB's query router directs queries to the
relevant shard as needed.
7. What are indexes in MongoDB?
MongoDB employs data structures known as indexes to enhance query performance, enabling the
database to swi ly locate documents according to the indexed fields. MongoDB offers support for a
range of index types.
8. How do you create a database in MongoDB?
You create a database implicitly by switching to it or explicitly by running the `use <database_name>`
command in the MongoDB shell. When you insert data into it, MongoDB will create the database if it
doesn't already exist.
9. How do you insert data into a MongoDB collec on?
You can insert data into a MongoDB collec on using the `insertOne()` or `insertMany()` method. You
provide a document or an array of documents to be inserted.
10. What is a replica set in MongoDB?
It is a group of servers that maintain the same data. It provides data redundancy and high availability.
One server acts as the primary, while others are secondary servers that replicate data from the
primary.
11. What are the data types supported by MongoDB?
MongoDB supports various data types, including string, number, boolean, date, array, object, null,
regex, and more. It also helps geospa al and binary data types.
12. How do you update documents in MongoDB?
You can update documents in MongoDB using methods like `updateOne()`, `updateMany(),` or
`findOneAndUpdate().` You specify the query to select the documents to update and provide an
update opera on.
13. What is the role of `_id` in MongoDB documents?
The `_id` field uniquely iden fies each document in a collec on. MongoDB uses it as the primary key,
and if not provided during document inser on, MongoDB generates a unique value for it.
14. How do you delete data from a MongoDB collec on?
You can delete data from a MongoDB collec on using methods like `deleteOne()`, `deleteMany()`, or
`findOneAndDelete()`. You specify a query to select the documents to delete.
15. What is a cursor in MongoDB, and when is it used?
A cursor in MongoDB is an iterator to retrieve and process documents from query results. Cursors
are used when fetching large result sets, allowing you to retrieve documents in batches.
16. Can you explain the concept of data modeling in MongoDB?
Data modeling in MongoDB involves designing the structure of your documents and collec ons to
represent your data best and meet your applica on's requirements. It includes defining document
schemas, rela onships, and indexing strategies.
17. How is data consistency maintained in MongoDB?
MongoDB provides strong consistency within a single document but offers eventual consistency for
distributed data across mul ple nodes or shards. It controls data consistency levels by using
mechanisms like write concern and read preferences.
18. What is the role of collec ons in MongoDB?
Collec ons in MongoDB are containers for organizing and storing related documents. They act as the
equivalent of tables in rela onal databases, grouping similar data.
19. How do you perform a query in MongoDB?
You can perform queries in MongoDB using the `find()` method, where you specify criteria to filter
documents. You can also use various query operators to refine your queries.
20. Can you explain the concept of aggrega on in MongoDB?
MongoDB's aggrega on framework is a powerful tool designed for processing and transforming
documents within a collec on. With it, you can execute various opera ons such as grouping, sor ng,
and compu ng aggregate values on your dataset.
21. What is the difference between MongoDB and MySQL?
 MongoDB is a NoSQL database, while MySQL is a tradi onal rela onal database.
 MongoDB stores data in flexible, schema-less documents; MySQL uses structured tables with
fixed schemas.
 MongoDB is designed for horizontal scalability, while MySQL typically scales ver cally.
 MongoDB is o en used for unstructured or semi-structured data, while MySQL is commonly
used for structured data.
22. How do you backup a MongoDB database?
You can back up a MongoDB database using tools like `mongodump` or by configuring regular
snapshots at the file system or cluster level.
23. What are the main features of MongoDB?
Some prominent features of MongoDB include flexibility in data modeling, horizontal scalability,
support for unstructured data, powerful query language, automa c sharding, high availability with
replica sets, and geospa al capabili es.
24. What is the purpose of using MongoDB over other databases?
MongoDB is chosen over other databases for its ability to handle flexible, unstructured, and rapidly
changing data. It excels in scenarios where scalability, speed, and agility are essen al, such as web
and mobile applica ons, real- me analy cs, and content management systems. Its horizontal scaling
capabili es also make it suitable for large-scale data storage and processing.
MongoDB Intermediate Interview ques ons:
1. How does MongoDB ensure high availability?
MongoDB guarantees robust availability via replica sets consis ng of mul ple MongoDB servers that
store iden cal data. This setup offers redundancy and seamless failover capabili es. In the event of a
primary node failure, an automa c process elects one of the secondary nodes to take over as the
new primary, thus ensuring uninterrupted service.
2. What is the role of a sharding key in MongoDB?
A sharding key determines how data is distributed across mul ple shards (database par ons) in a
sharded cluster. MongoDB uses a field in the document to decide which shard should store the
document. Choosing an appropriate sharding key is crucial for even data distribu on and efficient
queries.
3. Can you explain replica set elec ons in MongoDB?
Replica set elec ons occur when the primary node in a replica set becomes unavailable. In such
cases, the replica set members vote to elect a new primary. The node with the most votes becomes
the new primary, ensuring data availability and con nuity of service.
4. How does MongoDB handle transac ons?
MongoDB introduced mul -document transac ons in version 4.0, allowing you to perform ACID-
compliant transac ons. Transac ons ensure that a series of opera ons succeeds or fails, maintaining
data consistency.
5. What are the different types of indexes in MongoDB?
MongoDB supports various indexes, including single-field indexes, compound indexes, geospa al
indexes, text indexes, hashed indexes, and wildcard indexes.
6. Can you explain the aggrega on pipeline in MongoDB?
The Aggrega on Pipeline is a robust framework for performing data transforma ons and
computa ons on data stored in MongoDB. It consists of stages, each processing and transforming
data before passing it to the next stage. It's commonly used for complex data analysis and
aggrega on opera ons.
7. How do you monitor the performance of a MongoDB database?
You can monitor MongoDB using various tools and techniques. MongoDB provides built-in metrics
and logs, and external monitoring tools like MongoDB Atlas, MMS, and third-party solu ons can help
track performance, query execu on, and resource usage.
8. What is journaling in MongoDB?
In MongoDB, journaling is a durability feature that ensures data is wri en to a journal (write-ahead
log) before it's wri en to data files. This provides crash recovery and data consistency guarantees.
9. How does MongoDB handle replica on and failover?
MongoDB uses replica sets for replica on and failover. Data is replicated to secondary nodes, and
when a primary node failure occurs, one of the secondaries is automa cally elected as the new
primary to maintain high availability.
10. What are the different types of sharding strategies in MongoDB?
MongoDB supports various sharding strategies, including range-based sharding, hash-based
sharding, and tag-aware sharding. The choice of strategy depends on the data distribu on and query
pa erns.
11. Can you explain the read and write concerns in MongoDB?
Read and Write concerns in MongoDB allow you to specify the data consistency and
acknowledgment required for read and write opera ons. They include op ons like "majority,"
"acknowledged," and "unacknowledged."
12. How do you scale a MongoDB database?
You can scale MongoDB horizontally by adding more servers to a cluster, ver cally by upgrading
server hardware, or by using sharding to distribute data across mul ple servers in a sharded cluster.
13. What is the role of the WiredTiger storage engine in MongoDB?
Since version 3.2 of MongoDB, WiredTiger has served as the primary storage engine responsible for
data storage, compression, and caching, thereby enhancing both performance and concurrency.
14. How do you implement security in MongoDB?
MongoDB provides a range of security capabili es, including authen ca on, role-based access
control (RBAC), SSL/TLS encryp on, audi ng, and network security, ensuring data safeguarding and
preven ng unauthorized access.
15. Can you explain how MongoDB handles large data sets?
MongoDB can handle large data sets using horizontal scaling (sharding), op mized indexing, and
efficient storage mechanisms like WiredTiger. It also provides tools for data par oning and
distribu on.
16. What is the difference between embedded documents and references in MongoDB?
Embedded documents are nested within another document, while references are links or references
to documents in separate collec ons. Embedded documents are used for denormaliza on and
improved query performance, while references maintain data integrity.
17. How do you op mize query performance in MongoDB?
You can op mize query performance by crea ng appropriate indexes, using the Aggrega on Pipeline,
minimizing the number of queries, and op mizing query pa erns to leverage the query planner.
18. What are capped collec ons in MongoDB?
Capped collec ons are fixed-size collec ons that maintain data inser on order. Once the collec on
reaches its size limit, old data is automa cally overwri en by new data. They are o en used for
logging and event tracking.
19. How does MongoDB handle schema migra ons?
MongoDB's flexible schema makes it easier to evolve the data model over me. When schema
changes are required, applica ons can handle data migra on using techniques like in-place updates
or background processes.
20. What are the common pi alls in MongoDB data modeling?
Common pi alls include not choosing an appropriate sharding key, not understanding query
pa erns, not considering index size, and failing to denormalize data when necessary.
21. Can you explain the concept of GridFS in MongoDB?
GridFS represents a MongoDB standard designed to handle storing and retrieving substan al files,
such as images, videos, and binary data. This approach involves breaking down large files into smaller
segments and then saving them as individual documents within collec ons. This method enables the
efficient handling, retrieval, and administra on of such files.
22. How do you manage sessions in MongoDB?
MongoDB provides a session management API for managing mul -statement transac ons. Sessions
allow you to start and commit transac ons, ensuring data consistency.
23. What are the best prac ces for index crea on in MongoDB?
Best prac ces include crea ng indexes based on query pa erns, avoiding too many indexes, using
compound indexes effec vely, and periodically reviewing and maintaining indexes for op mal
performance.
24. How does MongoDB integrate with other data analysis tools?
MongoDB can integrate with various data analysis tools and frameworks through connectors, drivers,
and plugins. Popular tools like Apache Spark and Hadoop have connectors for MongoDB data.
25. What is the role of Oplog in MongoDB replica on?
Oplog (short for "opera on log") is a capped collec on that records all write opera ons in the
primary node of a replica set. Secondary nodes use the oplog to replicate changes and maintain data
consistency with the primary. It plays a crucial role in replica on and failover processes.
MongoDB Advanced Interview ques ons:
1. How do you design a sharded MongoDB architecture for a large-scale applica on?
 To design a sharded MongoDB architecture for a large-scale applica on, consider the
following steps:
 Iden fy a sharding key that evenly distributes data across shards.
 Set up a shard cluster with mul ple shard servers.
 Configure a shard router (mongos) to route queries to the appropriate shards.
 Implement replica sets within each shard for high availability.
 Monitor and scale the cluster as needed to maintain performance.
2. Can you explain the complexi es involved in MongoDB data sharding?
MongoDB data sharding introduces complexi es such as choosing the right shard key, managing data
distribu on, ensuring data consistency, and handling shard rebalancing. Handling shard keys and
ensuring balanced data distribu on are key challenges.
3. What are the strategies for handling data consistency in distributed MongoDB deployments?
In distributed MongoDB deployments, you can achieve data consistency through various strategies:
 Read Preference: Specify read preferences to control which data is read.
 Write Concern: Use write concern levels to control the acknowledgment of write opera ons.
 Transac ons: MongoDB supports mul -document transac ons to ensure consistency across
documents.
4. How do you handle data migra on in a live MongoDB environment?
Use tools like MongoDB's `mongodump` and `mongorestore` to perform live data migra ons. These
tools allow you to export data from one cluster and import it into another while minimizing
down me.
5. Can you explain the internals of the WiredTiger storage engine?
In MongoDB, WiredTiger is the default storage engine. It supports document-level locking,
compression, and data durability through write-ahead logging (WAL). It uses B-trees and LSM trees
for data storage.
6. What are the best prac ces for disaster recovery in MongoDB?
Disaster recovery best prac ces in MongoDB include regular backups, offsite storage, automated
backup processes, and tes ng backup restora on procedures. Implemen ng replica on and having a
well-defined recovery plan is crucial.
7. How do you perform advanced data aggrega on opera ons in MongoDB?
MongoDB offers the Aggrega on Framework, allowing for complex data aggrega on opera ons. You
can use operators like `$group`, `$project`, and `$lookup` to perform opera ons like filtering,
grouping, and joining data.
8. What are the considera ons for choosing shard keys in a highly distributed environment?
Consider even data distribu on, query pa erns, and scalability when choosing shard keys. Avoid
monotonically increasing keys to prevent hotspots. Use hashed shard keys for be er distribu on.
9. How do you troubleshoot performance issues in a sharded MongoDB cluster?
Troubleshoo ng performance in a sharded MongoDB cluster involves monitoring metrics, iden fying
slow queries, op mizing indexes, and scaling resources where needed. Analyzing the query execu on
plan is crucial.
10. Can you explain the process of tuning Read and Write opera ons in high-load environments?
In high-load environments, you can op mize read and write opera ons by adjus ng the MongoDB
configura on parameters, using appropriate indexes, and employing caching mechanisms like Redis
or Memcached.
11. How does MongoDB handle network par oning and split-brain scenarios?
MongoDB uses a replica set and an internal consensus algorithm to handle network par oning
scenarios. In split-brain scenarios, priority se ngs and automa c failover can help maintain data
consistency.
12. What are the best prac ces for securing a MongoDB cluster in a public cloud environment?
Best prac ces for securing MongoDB in a public cloud environment include network security groups,
authen ca on, role-based access control, rest and transit encryp on, and regularly applying security
patches.
13. How do you automate MongoDB deployments in a DevOps environment?
Automa on tools like Ansible, Terraform, or Kubernetes can be used to automate MongoDB
deployments in a DevOps environment. Infrastructure as Code (IaC) principles are o en applied.
14. Can you discuss the challenges of integra ng MongoDB with big data technologies?
Integra ng MongoDB with big data technologies like Hadoop, Spark, or Ka a can be challenging. You
may use connectors or ETL tools to transfer and process data between MongoDB and these systems.
15. How do you op mize MongoDB for IoT applica ons with high inges on rates?
To op mize MongoDB for IoT applica ons, use sharding, me-series data models, and proper
indexing. Implement data reten on policies and consider using edge compu ng for data
preprocessing.
16. What are the trade-offs between different replica on strategies in MongoDB?
MongoDB offers primary-secondary replica on, replica sets, and sharding. Each has trade-offs
regarding data consistency, failover, and read scalability. Choose the replica on strategy that suits
your applica on's needs.
17. How do you manage large-scale data migra ons in MongoDB?
For large-scale data migra ons, use tools like MongoDB Atlas Data Lake or data pipeline solu ons like
Apache Ka a. Plan for data valida on and verifica on to ensure data integrity.
18. What are the advanced techniques for monitoring MongoDB clusters?
Use monitoring tools like MongoDB Cloud Manager, Prometheus, or Grafana to track key
performance metrics, resource u liza on, and cluster health. Set up alerts for proac ve issue
detec on.
19. How do you ensure data integrity in a MongoDB transac on?
MongoDB supports mul -document transac ons to ensure data integrity. You can use transac ons to
group mul ple opera ons into a single unit of work, allowing for atomicity, consistency, isola on,
and durability (ACID).
20. Can you explain the role of consensus algorithms in MongoDB cluster management?
MongoDB uses the Ra consensus algorithm to replicate set elec ons and leader selec on. Ra
ensures that the cluster maintains a consistent state and can recover from failures.
21. How do you handle schema evolu on in MongoDB for agile development prac ces?
MongoDB's flexible schema allows for agile development prac ces. Developers can evolve the
schema by adding or removing fields as needed, and versioning data structures may be necessary for
compa bility.
22. What are the challenges and solu ons for backup and restora on in large MongoDB
deployments?
Challenges in large MongoDB deployments include data volume, backup frequency, and reten on
policies. Solu ons involve using incremental backups, snapshots, and offsite storage with efficient
data deduplica on.
23. How does MongoDB interact with microservices architectures?
MongoDB can be used as a data store in microservices architectures. Each microservice can have its
database or share it with others, depending on data isola on and coupling requirements.
24. Can you discuss the impact of network latency on MongoDB’s performance and scalability?
Network latency can impact MongoDB's performance and scalability, especially in geographically
distributed deployments. Techniques like read preference configura on and sharding can help
mi gate latency issues.
25. What are the future trends and expected developments in MongoDB?
While I cannot provide real- me informa on, MongoDB's future trends may include enhanced
support for mul -cloud deployments, further improvements in scalability and performance, and new
features to address evolving applica on needs in data management and analysis.
Express js Interview Ques ons
1. What is Express.js, and why do you use it?
Express.js is a web applica on framework for Node.js. It is an open-source pla orm for building
server-side applica ons in JavaScript. It provides excellent features and tools to developers to
develop web applica ons efficiently. Express.js helps developers to create and manage their
applica ons and offers a wide range of customiza on op ons.
2. How does Express.js handle rou ng?
Express.js has a simple rou ng system that allows developers to define and manage applica on
routes. Routes can be determined using the app.get() and app.post() methods. It can be associated
with callback func ons executed when a request is made to the route.
3. How does Express.js handle middleware?
Express.js has a middleware system that allows developers to define and manage middleware
func ons. These func ons can perform tasks such as authen ca on, valida on, or modifica on of
request and response objects. Middleware func ons are executed in the order they are defined.
They can be added to the applica on using the app.use() method.
4. How does Express.js handle request and response objects?
Express.js has a request and response object system that provides access to informa on about
incoming requests and outgoing responses. The request object contains informa on about the
incoming request, such as the URL, method, and headers. The response object is used to send a
response back to the client. Developers can use methods such as res.send(), res.json(), and
res.render() to send responses to the client.

6. What is the difference between a tradi onal server and an Express.js server?
A tradi onal server is a standalone server that is built and managed independently. While an
Express.js server is built using the Express.js framework. It runs on top of Node.js. Express.js provides
a simple and efficient way to create and manage web applica ons. It offers a wide range of features
and tools for handling rou ng, middleware, and request or response objects.
7. How does Express.js handle error handling?
Express.js provides an error-handling system that allows developers to define and manage error-
handling middleware func ons. These func ons can be used to catch and handle errors that make in
the applica on. It can be added to the applica on using the app.use() method.
8. What is a template engine, and how does Express.js use it?
A template engine is a tool used to generate HTML or other output based on dynamic data.
Express.js supports several template engines, such as EJS and Handlebars. These engines can
dynamically render HTML pages based on data stored in the applica on.
9. How does Express.js handle file uploads?
Express.js provides support for file uploads through middleware func ons and the request object.
Developers can use middleware func ons like multer or busboy to handle file uploads. It can access
the uploaded files through the request object.
10. Men on some of the databases with which Express JS is integrated.
Below are some of the databases that Express JS supports:
 MySQL
 MongoDB
 PostgreSQL
 SQLite
 Oracle
11. How does Express.js differ from other Node.js frameworks?
Express.js is a flexible framework that provides only the essen al features required for web
applica on development. On the other hand, other Node.js frameworks, such as Meteor, Sails.js, and
Koa.js, offer more features but may not be required for smaller projects. Express.js is a good choice
for simple, fast, and scalable web applica ons.
12. How do you handle errors in Express.js?
Express.js provides a built-in error-handling mechanism using the next() func on. When an error
occurs, you can pass it to the next middleware or route handler using the next() func on. You can
also add an error-handling middleware to your applica on that will be executed whenever an error
occurs.
13. What are middleware func ons in Express.js?
Middleware func ons are those func ons that can access and modify the request and response
objects in an Express applica on. They can add func onality to an applica on, such as logging,
authen ca on, and error handling.
14. What is a callback func on in Express.js?
A callback func on in Express.js is a type of func on that is called a er a specific ac on has occurred.
For example, a callback func on handles a successful or failed database query.
15. What is the difference between res.send() and res.json() in Express.js?
res.send() is used to send a response with any type of data (string, object, buffer, etc.). While
res.json() is used to send a JSON response. res.json() also sets the Content-Type header to
applica on or JSON.
16. What is the use of app.use() in Express.js?
app.use() is used to add middleware func ons to an Express applica on. It can be used to add global
middleware func ons or to add middleware func ons to specific routes.
17. What is the purpose of the next() func on in Express.js?
The next() func on is used to pass control from one middleware func on to the next func on. It is
used to execute the next middleware func on in the chain.
18. What is the difference between app.route() and app.use() in Express.js?
app.route() defines mul ple route handlers for a single route. While the app.use() func on is used to
add middleware func ons to an applica on.
19. What is the purpose of the req.params object in Express.js?
The req.params object is used to access route parameters in Express.js. Route parameters capture
values from the URL and pass them to the request handler.
20. What is the difference between req.query and req.params in Express.js?
req.query is used to access the query parameters in a URL. While req.params is used to access route
parameters in a URL.
21. What is the purpose of the app.locals object in Express.js?
The app.locals object stores applica on-level data in an Express.js applica on. This data is available
to all templates and routes.
REACTJS INTERVIEW QUESTIONS
1. What is ReactJS?
ReactJS is a JavaScript library used to build reusable components for the view layer in MVC
architecture. It is highly efficient and uses a virtual DOM to render components. It works on the
client side and is wri en in JSX.
2. Explain the MVC architecture?
The Model-View-Controller (MVC) framework is an architectural/design pa ern that separates an
applica on into three main logical components Model, View, and Controller. Each architectural
component is built to handle specific development aspects of an applica on. It isolates the business,
logic, and presenta on layer from each other
3. Explain the building blocks of React?
The five main building blocks of React are:
 Components: These are reusable blocks of code that return HTML.
 JSX: It stands for JavaScript and XML and allows you to write HTML in React.
 Props and State: props are like func on parameters and State is similar to variables.
 Context: This allows data to be passed through components as props in a hierarchy.
 Virtual DOM: It is a lightweight copy of the actual DOM which makes DOM manipula on
easier.
4. Explain props and state in React with differences
Props are used to pass data from one component to another. The state is local data storage that is
local to the component only and cannot be passed to other components.

5. What is virtual DOM in React?

React uses Virtual DOM which is like a lightweight copy of the actual DOM(a virtual representa on of
the DOM). So for every object that exists in the original DOM, there is an object for that in React
Virtual DOM. It is the same, but it does not have the power to directly change the layout of the
document. Manipula ng DOM is slow, but manipula ng Virtual DOM is fast as nothing gets drawn on
the screen. So each me there is a change in the state of our applica on, the virtual DOM gets
updated first instead of the real DOM.
6. What is JSX?
JSX is basically a syntax extension of regular JavaScript and is used to const name = "Learner";
create React elements. These elements are then rendered to the
React DOM. All the React components are wri en in JSX. To embed const element = (
any JavaScript expression in a piece of code wri en in JSX we will have <h1>
to wrap that expression in curly braces {}. Hello,
Example of JSX: The name wri en in curly braces { } signifies JSX {name}.Welcome to GeeksforGeeks.
</h1>
7. What are components and their type in React? );
A Component is one of the core building blocks of React. In other
words, we can say that every applica on you will develop in React will
be made up of pieces called components. Components make the task of building UIs much easier.
In React, we mainly have two types of components:
 Func onal Components: Func onal components are simply javascript func ons. We can
create a func onal component in React by wri ng a javascript func on.
 Class Components: The class components are a li le more complex than the func onal
components. The func onal components are not aware of the other components in your
program whereas the class components can work with each other. We can pass data from
one class component to another class component.
8. How do browsers read JSX?
In general, browsers are not capable of reading JSX and only can read pure JavaScript. The web
browsers read JSX with the help of a transpiler. Transpilers are used to convert JSX into JavaScript.
The transpiler used is called Babel

12. What is a key in React?


A “key” is a special string a ribute you need to include when crea ng lists of elements in React. Keys
are used in React to iden fy which items in the list are changed, updated, or deleted. In other words,
we can say that keys are used to give an iden ty to the elements in the lists.
13. How to write a comment in React?
There are two ways to write comments in React.
 Mul -line comment: We can write mul -line comments in React using the asterisk format /*
*/.
 Single line comment: We can write single comments in React using the double forward slash
//.
15. Explain the use of render method in React?
React renders HTML to the web page by using a func on called render(). The purpose of the func on
is to display the specified HTML code inside the specified HTML element. In the render() method, we
can read props and state and return our JSX code to the root component of our app.
16. What is state in React?
The state is an instance of React Component Class that can be defined as an object of a set of
observable proper es that control the behaviour of the component. In other words, the State of a
component is an object that holds some informa on that may change over the life me of the
component.
17. Explain props in React?
React allows us to pass informa on to a Component using something called props (which stands for
proper es). Props are objects which can be used inside a component
We can access any props inside from the component’s class to which the props is passed. The props
can be accessed as shown below:
this.props.propName;
18. What is higher-order component in React?
Higher-order components or HOC is the advanced method of reusing the component func onality
logic. It simply takes the original component and returns the enhanced component. HOC are
beneficial as they are easy to code and read. Also, helps to get rid of copying the same logic in every
component.
19. Explain the difference between func onal and class component in React?

20. Explain one way data binding in React?


ReactJS uses one-way data binding which can be Component to View or View to Component. It is
also known as one-way data flow, which means the data has one, and only one way to be transferred
to other parts of the applica on. In essence, this means child components are not able to update the
data that is coming from the parent component. It is easy to debug and less prone to errors.

React Intermediate Interview Questions


21. What is condi onal rendering in React?
Condi onal rendering in React involves selec vely rendering components based on specified
condi ons. By evalua ng these condi ons, developers can control which components are displayed,
allowing for dynamic and responsive user interfaces in React applica ons.
Let us look at this sample code to understand condi onal rendering.
{isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}
Here if the boolean isLoggedIn is false then the DisplayLoggedOut component will be rendered
otherwise DisplayLoggedIn component will be rendered.
22. What is react router?
React Router is a standard library for rou ng in React. It enables the naviga on among views of
various components in a React Applica on, allows changing the browser URL, and keeps the UI in
sync with the URL.
To install react router type the following command.
npm i react-router-dom
23. Explain the components of a react-router
The main components of a react-router are:
1. Router(usually imported as BrowserRouter): It is the parent component that is used to
store all of the other components. Everything within this will be part of the rou ng
func onality
2. Switch: The switch component is used to render only the first route that matches the
loca on rather than rendering all matching routes.
3. Route: This component checks the current URL and displays the component associated with
that exact path. All routes are placed within the switch components.
4. Link: The Link component is used to create links to different routes.
24. Explain the lifecycle methods of components
A React Component can go through four stages of its life as follows.
 Ini aliza on: This is the stage where the component is constructed with the given Props and
default state. This is done in the constructor of a Component Class.
 Moun ng: Moun ng is the stage of rendering the JSX returned by the render method itself.
 Upda ng: Upda ng is the stage when the state of a component is updated and the
applica on is repainted.
 Unmoun ng: As the name suggests Unmoun ng is the final step of the component lifecycle
where the component is removed from the page.
25. Explain the methods used in moun ng phase of components
Moun ng is the phase of the component lifecycle when the ini aliza on of the component is
completed and the component is mounted on the DOM and rendered for the first me on the
webpage. he moun ng phase consists of two such predefined func ons as described below
 componentWillMount() Func on: This func on is invoked right before the component is
mounted on the DOM.
 componentDidMount() Func on: This func on is invoked right a er the component is
mounted on the DOM.
26. What is this.setState func on in React?
We use the setState() method to change the state object. It ensures that the component has been
updated and calls for re-rendering of the component. The state object of a component may contain
mul ple a ributes and React allows using setState() func on to update only a subset of those
a ributes as well as using mul ple setState() methods to update each a ribute value independently.
27. What is the use of ref in React?
Refs are a func on provided by React to access the DOM element and the React element that you
might have created on your own. They are used in cases where we want to change the value of a
child component, without making use of props and all. They have wide func onality as we can use
callbacks with them.
The syntax to use ref is
const node = this.myCallRef.current;
28. What are hooks in React?
Hooks are a new addi on in React 16.8. They let developers use state and other React features
without wri ng a class. Hooks doesn’t violate any exis ng React concepts. Instead, Hooks provide a
direct API to react concepts such as props, state, context, refs and life-cycle
29. Explain the useState hook in React?
The most used hook in React is the useState() hook. It allows func onal components to manipulate
DOM elements before each render. Using this hook we can declare a state variable inside a func on
but only one state variable can be declared using a single useState() hook. Whenever the useState()
hook is used, the value of the state variable is changed and the new variable is stored in a new cell in
the stack.
We have to import this hook in React using the following syntax
import {useState} from 'react'
30. Explain the useEffect hook in react?
The useEffect hook in React eliminates the side effect of using class based components. It is used as
an alterna ve to componentDidUpdate() method. The useEffect hook accepts two arguments where
second argument is op onal.
useEffect(func on, dependency)
The dependency decides when the component will be updated again a er rendering.
31. What is React Fragments?
when we are trying to render more than one root element we have to put the en re content inside
the ‘div’ tag which is not loved by many developers. So since React 16.2 version, Fragments were
introduced, and we use them instead of the extraneous ‘div’ tag. The following syntax is used to
create fragment in react.
<React.Fragment>
<h2>Child-1</h2>
<p> Child-2</p>
</React.Fragment>
32. What is a react developer tool?
React Developer Tools is a Chrome DevTools extension for the React JavaScript library. A very useful
tool, if you are working on React.js applica ons. This extension adds React debugging tools to the
Chrome Developer Tools. It helps you to inspect and edit the React component tree that builds the
page, and for each component, one can check the props, the state, hooks, etc.
33. How to use styles in ReactJS?
CSS modules are a way to locally scope the content of your CSS file. We can create a CSS module file
by naming our CSS file as App.modules.css and then it can be imported inside App.js file using the
special syntax men oned below.
Syntax:
import styles from './App.module.css';
34. Explain styled components in React?
Styled-component Module allows us to write CSS within JavaScript in a very modular and reusable
way in React. Instead of having one global CSS file for a React project, we can use styled-component
for enhancing the developer experience. It also removes the mapping between components and
styles – using components as a low-level styling construct
The command to install styled components is
npm i styled-components
Using the below code we can custom style a bu on in React
Javascript
import styled from 'styled-components'

const Bu on = styled.div`
width : 100px ;
cursor: pointer ;
text-decora on : none;
`

export default Bu on;


35. What is prop drilling and its disadvantages?
Prop drilling is basically a situa on when the same data is being sent at almost every level due to
requirements in the final level. The problem with Prop Drilling is that whenever data from the Parent
component will be needed, it would have to come from each level, Regardless of the fact that it is
not needed there and simply needed in last.
For further reading, check out our dedicated ar cle on Intermediate ReactJS Intermediate Interview
Ques ons. Inside, you’ll discover over 20 ques ons with detailed answers.
React Interview Ques ons For Experienced
Here, we cover advanced react interview ques ons with answers for experienced professionals,
who have over 5+ years of experience.
36. What is custom hooks in React?
Custom hooks are normal JavaScript func ons whose names start with “use” and they may call other
hooks. We use custom hooks to maintain the DRY concept that is Don’t Repeat Yourself. It helps us to
write a logic once and use it anywhere in the code.
37. How to op mize a React code?
We can improve our react code by following these prac ces:
 Using binding func ons in constructors
 Elimina ng the use of inline a ributes as they slow the process of loading
 Avoiding extra tags by using React fragments
 Lazy loading
38. What is the difference between useref and createRef in React ?

39. What is react-redux?


React-redux is a state management tool which makes it easier to pass these states from one
component to another irrespec ve of their posi on in the component tree and hence prevents the
complexity of the applica on. As the number of components in our applica on increases it becomes
difficult to pass state as props to mul ple components. To overcome this situa on we use react-
redux
40. What are benefits of using react-redux?
They are several benfits of using react-redux such as:
 It provides centralized state management i.e. a single store for whole applica on
 It op mizes performance as it prevents re-rendering of component
 Makes the process of debugging easier
 Since it offers persistent state management therefore storing data for long mes become
easier
41. Explain the core components of react-redux?
There are four fundamental concepts of redux in react which decide how the data will flow through
components
 Redux Store: It is an object that holds the applica on state
 Acr on Creators: These are unc ons that return ac ons (objects)
 Ac ons: Ac ons are simple objects which conven onally have two proper es- type and
payload
 Reducers: Reducers are pure func ons that update the state of the applica on in response to
ac ons
42. How can we combine mul ple reducers in React?
When working with Redux we some mes require mul ple reducers. In many cases, mul ple ac ons
are needed, resul ng in the requirement of mul ple reducers. However, this can become
problema c when crea ng the Redux store. To manage the mul ple reducers we have func on
called combineReducers in the redux. This basically helps to combine mul ple reducers into a single
unit and use them.
Syntax:
import { combineReducers } from "redux";
const rootReducer = combineReducers({
books: BooksReducer,
ac veBook: Ac veBook
});
43. What is context API?
Context API is used to pass global variables anywhere in the code. It helps when there is a need for
sharing state between a lot of nested components. It is light in weight and easier to use, to create a
context just need to call React.createContext(). It eliminates the need to install other dependencies
or third-party libraries like redux for state management. It has two proper es Provider and
Consumer.
44. Explain provider and consumer in ContextAPI?
A provider is used to provide context to the whole applica on whereas a consumer consume the
context provided by nearest provider. In other words The Provider acts as a parent it passes the state
to its children whereas the Consumer uses the state that has been passed.
45. Explain CORS in React?
In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make
requests to the server deployed at a different domain. As a reference, if the frontend and backend
are at two different domains, we need CORS there.
We can setup CORS evironment in frontend using two methods:
 axios
 fetch
46. What is axios and how to use it in React?
Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST
endpoints. This library is very useful to perform CRUD opera ons.
 This popular library is used to communicate with the backend. Axios supports the Promise
API, na ve to JS ES6.
 Using Axios we make API requests in our applica on. Once the request is made we get the
data in Return, and then we use this data in our project.
To install aixos package in react use the following command.
npm i axios
48. Explain why and how to update state of components using callback?
It is advised to use a callback-based approach to update the state using setState because it solves lots
of bugs upfront that may occur in the future.We can use the following syntax to update state using
callback
this.setState(st => {
return(
st.stateName1 = state1UpdatedValue,
st.stateName2 = state2UpdatedValue
)
})
49. What is React-Material UI?
React Material UI is a framework leveraging React library, offering prebuilt components for crea ng
React applica ons. Developed by Google in 2014, it’s compa ble with JavaScript frameworks like
Angular.js and Vue.js. Renowned for its quality designs and easy customiza on, it’s favored by
developers for rapid development.
50. What is flux architecture in redux?
Flux is AN architecture that Facebook uses internally when opera ng with React. It is merely a
replacement quite an architecture that enhances React and also the idea of unidirec onal data flow.

React Interview Question and Answers (2024) –


Advance Level
1. What is custom hooks in React?
Custom hooks are normal JavaScript func ons whose names start with “use” and they may call other
hooks. We use custom hooks to maintain the DRY concept that is Don’t Repeat Yourself. It helps us to
write a logic once and use it anywhere in the code.
2. How to op mize a React code?
We can improve our react code by following these prac ces:
 Using binding func ons in constructors
 Elimina ng the use of inline a ributes as they slow the process of loading
 Avoiding extra tags by using React fragments
 Lazy loading
3. What is the difference between useref and createRef in React ?

4. What is react-redux?
React-redux is a state management tool which makes it easier to pass these states from one
component to another irrespec ve of their posi on in the component tree and hence prevents the
complexity of the applica on. As the number of components in our applica on increases it becomes
difficult to pass state as props to mul ple components. To overcome this situa on we use react-
redux
5. What are benefits of using react-redux?
They are several benfits of using react-redux such as:
 It provides centralized state management i.e. a single store for whole applica on
 It op mizes performance as it prevents re-rendering of component
 Makes the process of debugging easier
 Since it offers persistent state management therfore storing data for long mes become
easier
6. Explain the core components of react-redux?
There are four fundamental concepts of redux in react which decide how the data will flow through
components
 Redux Store: It is an object that holds the applica on state
 Acr on Creators: These are unc ons that return ac ons (objects)
 Ac ons: Ac ons are simple objects which conven onally have two proper es- type and
payload
 Reducers: Reducers are pure func ons that update the state of the applica on in response to
ac ons
7. How can we combine mul ple reducers in React?
When working with Redux we some mes require mul ple reducers. In many cases, mul ple ac ons
are needed, resul ng in the requirement of mul ple reducers. However, this can become
problema c when crea ng the Redux store. To manage the mul ple reducers we have func on
called combineReducers in the redux. This basically helps to combine mul ple reducers into a single
unit and use them.

8. What is context API?


Context API is used to pass global variables anywhere in the code. It helps when there is a need for
sharing state between a lot of nested components. It is light in weight and easier to use, to create a
context just need to call React.createContext(). It eliminates the need to install other dependencies
or third-party libraries like redux for state management. It has two proper es Provider and
Consumer.
9. Explain provider and consumer in ContextAPI?
A provider is used to provide context to the whole applica on whereas a consumer consume the
context provided by nearest provider. In other words The Provider acts as a parent it passes the state
to its children whereas the Consumer uses the state that has been passed.
10. Explain CORS in React?
In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make
requests to the server deployed at a different domain. As a reference, if the frontend and backend
are at two different domains, we need CORS there.
We can setup CORS evironment in frontend using two methods:
 axios
 fetch
11. What is axios and how to use it in React?
Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST
endpoints. This library is very useful to perform CRUD opera ons.
 This popular library is used to communicate with the backend. Axios supports the Promise
API, na ve to JS ES6.
 Using Axios we make API requests in our applica on. Once the request is made we get the
data in Return, and then we use this data in our project.
To install aixos package in react use the following command.
npm i axios

13. Explain why and how to update state of components using callback?
It is advised to use a callback-based approach to update the state using setState because it solves lots
of bugs upfront that may occur in the future.We can use the following syntax to update state using
callback
this.setState(st => {
return(
st.stateName1 = state1UpdatedValue,
st.stateName2 = state2UpdatedValue
)
})
14. What is React-Material UI?
React Material UI is a framework built upon React library which contains predefined components to
create React applica ons. Material UI is basically a design language built by Google in 2014 and
works with various JavaScript frameworks apart from React such as Angular.js and Vue.js. The quality
of the inbuilt designs of Material UI and its easy implementa on makes it the first choice of most
developers. The inbuilt components are also customizable so it helps easily recreate the designs.
15. What is flux architecture in redux?
Flux is AN architecture that Facebook uses internally when opera ng with React. It is merely a
replacement quite an architecture that enhances React and also the idea of unidirec onal data flow.
16. Explain the useMemo hook in react?
The useMemo is a hook used in the func onal component of react that returns a memoized value. In
Computer Science, memoiza on is a concept used in general when we don’t need to recompute the
func on with a given argument for the next me as it returns the cached result. A memoized
func on remembers the results of output for a given set of inputs.
17. Does React useState Hook update immediately ?
React do not update immediately, although it seems immediate at first glance. React keep track of
the states by queuing them in the order they are called. React queue all the changes to be made and
update once the component Re-render which is not immediate. This is how React knows which value
corresponds to which state. It goes as per the queue every me the component tries to re-render.
18. When to use useCallback, useMemo and useEffect ?
 useEffect is a func on that can be used as an alterna ve of lifecycle methods such as
componentDidMount, componenetWillUnmount, componentDidUpdate in funcitonal
components
 useCallback can be used when we want to prevent unnecessary renders from the chld
components. It helpd to resolve side effects
 useMemo is used when we want to re-render on based on cache values as makes the
applica on faster
19. Explain the types of router in React?
There are basically three types of router in React:
 Memory Router:The memory router keeps the URL changes in memory not in the user
browsers.
 Browser Router : It uses HTML 5 history API (i.e. pushState, replaceState, and popState API)
to keep your UI in sync with the URL
 Hash Router: Hash router uses client-side hash rou ng. It uses the hash por on of the URL
(i.e. window.loca on.hash) to keep your UI in sync with the URL.
20. What is StrictMode in React ?
The React StrictMode can be viewed as a helper component that allows developers to code
efficiently and brings to their a en on any suspicious code which might have been accidentally
added to the applica on. The StrictMode can be applied to any sec on of the applica on, not
necessarily to the en re applica on
NODEJS INTERVIEW QUESTIONS:
1. What is Node.js?
Node.js is a JavaScript engine used for execu ng JavaScript code outside the browser. It is normally
used to build the backend of the applica on and is highly scalable.
2. What is the difference between Node.js and JavaScript?
JavaScript is a scrip ng language whereas Node.js is an engine that provides the run me
environment to run JavaScript code.

3. Is Node.js single-threaded?

Yes, Node.js is single-threaded by default. However, it u lizes event-driven architecture and non-
blocking I/O opera ons to handle mul ple concurrent requests efficiently, enabling scalability and
high performance in applica ons.
4. What kind of API func on is supported by Node.js?
There are two types of API func ons supported by Node.js:
 Synchronous: These API func ons are used for blocking code.
 Asynchronous: These API func ons are used for non-blocking code.
5. What is the difference between Synchronous and Asynchronous func ons?

6. What is a module in Node.js?


In Node.js Applica on, a Module can be considered as a block of code that provide a simple or
complex func onality that can communicate with external applica on. Modules can be organized in
a single file or a collec on of mul ple files/folders. Modules are useful because of their reusability
and ability to reduce the complexity of code into smaller pieces. Some examples of modules are.
h p, fs, os, path, etc.
7. What is npm and its advantages?
npm (Node Package Manager) is the default package manager for Node.js. It allows developers to
discover, share, and reuse code packages easily. Its advantages include dependency management,
version control, centralized repository, and seamless integra on with Node.js projects.
8. What is middleware?
Middleware is the func on that works between the request and the response cycle. Middleware gets
executed a er the server receives the request and before the controller sends the response.
9. How does Node.js handle concurrency even a er being single-threaded?
Node.js handles concurrency by using asynchronous, non-blocking opera ons. Instead of wai ng for
one task to complete before star ng the next, it can ini ate mul ple tasks and con nue processing
while wai ng for them to finish, all within a single thread.
10. What is control flow in Node.js?
Control flow in Node.js refers to the sequence in which statements and func ons are executed. It
manages the order of execu on, handling asynchronous opera ons, callbacks, and error handling to
ensure smooth program flow.
11. What do you mean by event loop in Node.js?
The event loop in Node.js is a mechanism that allows it to handle mul ple asynchronous tasks
concurrently within a single thread. It con nuously listens for events and executes associated
callback func ons.
12. What is the order in which control flow statements get executed?
The order in which the statements are executed is as follows:
 Execu on and queue handling
 Collec on of data and storing it
 Handling concurrency
 Execu ng the next lines of code
13. What are the main disadvantages of Node.js?
Here are some main disadvantages of Node.js listed below:
 Single-threaded nature: May not fully u lize mul -core CPUs, limi ng performance.
 NoSQL preference: Rela onal databases like MySQL aren’t commonly used.
 Rapid API changes: Frequent updates can introduce instability and compa bility issues.
14. What is REPL in Node.js?
REPL in Node.js stands for Read, Evaluate, Print, and Loop. It is a computer environment similar to
the shell which is useful for wri ng and debugging code as it executes the code in on go.
15. How to import a module in Node.js?
We use the require module to import the External libraries in Node.js. The result returned by
require() is stored in a variable which is used to invoke the func ons using the dot nota on.
16. What is the difference between Node.js and AJAX?
Node.js is a JavaScript run me environment that runs on the server side whereas AJAX is a client-side
programming language that runs on the browser.
17. What is package.json in Node.js?
package.json in Node.js is a metadata file that contains project-specific informa on such as
dependencies, scripts, version, author details, and other configura on se ngs required for
managing and building the project.

19. What is the most popular Node.js framework used these days?
The most famous Node.js framework used is Express.js as it is highly scalable, efficient, and requires
very few lines of code to create an applica on.
20. What are promises in Node.js?
A promise is basically an advancement of callbacks in NodeJS. In other words, a promise is a
JavaScript object which is used to handle all the asynchronous data opera ons. While developing an
applica on you may encounter that you are using a lot of nested callback func ons which causes a
problem of callback hell. Promises solve this problem of callback hell.
Intermediate Node.js Interview Ques ons and Answers
In this set we will be looking at intermediate Node Interview Ques on for candidates with over 2
years of experience.
21. What is event-driven programming in Node.js?
Event-driven programming is used to synchronize the occurrence of mul ple events and to make the
program as simple as possible. The basic components of an Event-Driven Program are:
 A callback func on ( called an event handler) is called when an event is triggered.
 An event loop that listens for event triggers and calls the corresponding event handler for
that event.
22. What is buffer in Node.js?
The Buffer class in Node.js is used to perform opera ons on raw binary data. Generally, Buffer refers
to the par cular memory loca on in memory. Buffer and array have some similari es, but the
difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it
can not be resizable. Each integer in a buffer represents a byte. console.log() func on is used to print
the Buffer instance.
23. What are streams in Node.js?
Streams are a type of data-handling method and are used to read or write input into output
sequen ally. Streams are used to handle reading/wri ng files or exchanging informa on in an
efficient way. The stream module provides an API for implemen ng the stream interface. Examples
of the stream object in Node.js can be a request to an HTTP server and process.stdout are both
stream instances.
24. Explain crypto module in Node.js
The crypto module is used for encryp ng, decryp ng, or hashing any type of data. This encryp on
and decryp on basically help to secure and add a layer of authen ca on to the data. The main use
case of the crypto module is to convert the plain readable text to an encrypted format and decrypt it
when required.
25. What is callback hell?
Callback hell is an issue caused due to a nested callback. This causes the code to look like a pyramid
and makes it unable to read To overcome this situa on we use promises.
26. Explain the use of mers module in Node.js
The Timers module in Node.js contains various func ons that allow us to execute a block of code or a
func on a er a set period of me. The Timers module is global, we do not need to use require() to
import it.
It has the following methods:
 setTimeout() method
 setImmediate() method
 setInterval() method
27. Difference between setImmediate() and process.nextTick() methods
The process.nextTick() method is used to add a new callback func on at the start of the next event
queue. it is called before the event is processed. The setImmediate is called at the check phase of the
next event queue. It is created in the poll phase and is invoked during the check phase.
28. What is the difference between setTimeout() and setImmediate() method?
The setImmediate func on is used to execute a par cular script immediately whereas the
setTimeout func on is used to hold a func on and execute it a er a specified period of me.
29. What is the difference between spawn() and fork() method?
Both these methods are used to create new child processes the only difference between them is that
spawn() method creates a new func on that Node runs from the command line whereas fork()
func on creates an instance of the exis ng fork() method and creates mul ple workers to perform
on the same task.
30. Explain the use of passport module in Node.js
The passport module is used for adding authen ca on features to our website or web app. It
implements authen ca on measure which helps to perform sign-in opera ons.
31. What is fork in Node.js?
Fork is a method in Node.js that is used to create child processes. It helps to handle the increasing
workload. It creates a new instance of the engine which enables mul ple processes to run the code.
32. What are the three methods to avoid callback hell?
The three methods to avoid callback hell are:
 Using async/await()
 Using promises
 Using generators
33. What is body-parser in Node.js?
Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming
request bodies in a middleware before you handle it. It is an NPM module that processes data sent in
HTTP requests.
34. What is CORS in Node.js?
The word CORS stands for “Cross-Origin Resource Sharing”. Cross-Origin Resource Sharing is an HTTP-
header based mechanism implemented by the browser which allows a server or an API to indicate
any origins (different in terms of protocol, hostname, or port) other than its origin from which the
unknown origin gets permission to access and load resources. The cors package available in the npm
registry is used to tackle CORS errors in a Node.js applica on.
35. Explain the tls module in Node.js?
The tls module provides an implementa on of the Transport Layer Security (TLS) and Secure Socket
Layer (SSL) protocols that are built on top of OpenSSL. It helps to establish a secure connec on on
the network.
For further reading, check out our dedicated ar cle on Intermediate Node Interview Ques ons and
Answers. Inside, you’ll discover 20+ ques ons with detailed answers.
Advanced Node.js Interview Ques ons for Experienced
In this set we will be covering Node interview ques on for experienced developers with over 5 years
of experience.
36. What is a cluster in Node.js?
Due to a single thread in node.js, it handles memory more efficiently because there are no mul ple
threads due to which no thread management is needed. Now, to handle workload efficiently and to
take advantage of computer mul -core systems, cluster modules are created that provide us the way
to make child processes that run simultaneously with a single parent process.
37. Explain some of the cluster methods in Node.js
 Fork(): It creates a new child process from the master. The isMaster returns true if the
current process is master or else false.
 isWorker: It returns true if the current process is a worker or else false.
 process: It returns the child process which is global.
 send(): It sends a message from worker to master or vice versa.
 kill(): It is used to kill the current worker.
38. How to manage sessions in Node.js?
Session management can be done in node.js by using the express-session module. It helps in saving
the data in the key-value form. In this module, the session data is not saved in the cookie itself, just
the session ID.
39. Explain the types of streams in Node.js
Types of Stream:
 Readable stream: It is the stream from where you can receive and read the data in an
ordered fashion. However, you are not allowed to send anything. For example,
fs.createReadStream() lets us read the contents of a file.
 Writable stream: It is the stream where you can send data in an ordered fashion but you are
not allowed to receive it back. For example, fs.createWriteStream() lets us write data to a
file.
 Duplex stream: It is the stream that is both readable and writable. Thus you can send in and
receive data together. For example, net.Socket is a TCP socket.
 Transform stream: It is the stream that is used to modify the data or transform it as it is read.
The transform stream is basically a duplex in nature. For example, zlib.createGzip stream is
used to compress the data using gzip.
40. How can we implement authen ca on and authoriza on in Node.js?
Authen ca on is the process of verifying a user’s iden ty while authoriza on is determining what
ac ons can be performed. We use packages like Passport and JWT to implement authen ca on and
authoriza on.
41. Explain the packages used for file uploading in Node.js?
The package used for file uploading in Node.js is Multer. The file can be uploaded to the server using
this module. There are other modules in the market but Multer is very popular when it comes to file
uploading. Multer is a node.js middleware that is used for handling mul part/form-data, which is a
mostly used library for uploading files.
42. Explain the difference between Node.js and server-side scrip ng languages like Python
Node.js is the best choice for asynchronous programming Python is not the best choice for
asynchronous programming. Node.js is best suited for small projects to enable func onality that
needs less amount of scrip ng. Python is the best choice if you’re developing larger projects. Node.js
is best suited for memory-intensive ac vi es. Not recommended for memory-intensive ac vi es.
Node.js is a be er op on if your focus is exactly on web applica ons and website development. But,
Python is an all-rounder and can perform mul ple tasks like- web applica ons, integra on with back-
end applica ons, numerical computa ons, machine learning, and network programming. Node.js is
an ideal and vibrant pla orm available right now to deal with real- me web applica ons. Python
isn’t an ideal pla orm to deal with real- me web applica ons. The fastest speed and great
performance are largely due to Node.js being based on Chrome’s V8 which is a very fast and
powerful engine. Python is slower than Node.js, As Node.js is based on fast and powerful Chrome’s
V8 engine, Node.js u lizes JavaScript interpreter. Python using PyPy as Interpreter. In case of error
handling and debugging Python beats Node.js. Error handling in Python takes significantly very li le
me and debugging in Python is also very easy compared to Node.js.
43. How to handle database connec on in Node.js?
To handle database connec on in Node.js we use the driver for MySQL and libraries like Mongoose
for connec ng to the MongoDB database. These libraries provide methods to connect to the
database and execute queries.
44. How to read command line arguments in Node.js?
Command-line arguments (CLI) are strings of text used to pass addi onal informa on to a program
when an applica on is running through the command line interface of an opera ng system. We can
easily read these arguments by the global object in node i.e. process object. Below is the approach:
Step 1: Save a file as index.js and paste the below code inside the file.
Javascript
let arguments = process.argv ;

console.log(arguments) ;
Step 2: Run the index.js file using the below command:
node index.js
45. Explain the Node.js redis module
Redis is an Open Source store for storing data structures. It is used in mul ple ways. It is used as a
database, cache, and message broker. It can store data structures such as strings, hashes, sets, sorted
sets, bitmaps, indexes, and streams. Redis is very useful for Node.js developers as it reduces the
cache size which makes the applica on more efficient. However, it is very easy to integrate Redis with
Node.js applica ons.
46. What is web socket?
Web Socket is a protocol that provides full-duplex (mul way) communica on i.e. allows
communica on in both direc ons simultaneously. It is a modern web technology in which there is a
con nuous connec on between the user’s browser (client) and the server. In this type of
communica on, between the web server and the web browser, both of them can send messages to
each other at any point in me. Tradi onally on the web, we had a request/response format where a
user sends an HTTP request and the server responds to that. This is s ll applicable in most cases,
especially those using RESTful API. But a need was felt for the server to also communicate with the
client, without ge ng polled(or requested) by the client. The server in itself should be able to send
informa on to the client or the browser. This is where Web Socket comes into the picture.
47. Explain the u l module in Node.js
The U l module in node.js provides access to various u lity func ons. There are various u lity
modules available in the node.js module library.
 OS Module: Opera ng System-based u lity modules for node.js are provided by the OS
module.
 Path Module: The path module in node.js is used for transforming and handling various file
paths.
 DNS Module: DNS Module enables us to use the underlying Opera ng System name
resolu on func onali es. The actual DNS lookup is also performed by the DNS Module.
 Net Module: Net Module in node.js is used for the crea on of both client and server. Similar
to DNS Module this module also provides an asynchronous network wrapper.
48. How to handle environment variables in Node.js?
We use process.env to handle environment variables in Node.js. We can specify environment
configura ons as well as keys in the .env file. To access the variable in the applica on, we use the
“process.env.VARIABLE_NAME” syntax. To use it we have to install the dotenv package using the
below command:
npm install dotenv
49. Explain DNS module in Node.js
DNS is a node module used to do name resolu on facility which is provided by the opera ng system
as well as used to do an actual DNS lookup. Its main advantage is that there is no need for
memorizing IP addresses – DNS servers provide a ni y solu on for conver ng domain or subdomain
names to IP addresses.
50. What are child processes in Node.js?
Usually, Node.js allows single-threaded, non-blocking performance but running a single thread in a
CPU cannot handle increasing workload hence the child_process module can be used to spawn child
processes. The child processes communicate with each other using a built-in messaging system.
51. What is tracing in Node.js?
The Tracing Objects are used for a set of categories to enable and disable the tracing. When tracing
events are created then tracing objects is disabled by calling tracing.enable() method and then
categories are added to the set of enabled trace and can be accessed by calling tracing.categories.
Node Interview Questions and Answers (2024) –
Intermediate Level
1. What is event-driven programming in Node.js?
Event-driven programming is used to synchronize the occurrence of mul ple events and to make the
program as simple as possible. The basic components of an Event-Driven Program are:
 A callback func on ( called an event handler) is called when an event is triggered.
 An event loop that listens for event triggers and calls the corresponding event handler for
that event.
2. What is buffer in Node.js?
The Buffer class in Node.js is used to perform opera ons on raw binary data. Generally, Buffer refers
to the par cular memory loca on in memory. Buffer and array have some similari es, but the
difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it
can not be resizable. Each integer in a buffer represents a byte. console.log() func on is used to print
the Buffer instance.
3. What are streams in Node.js?
Streams are a type of data-handling method and are used to read or write input into output
sequen ally. Streams are used to handle reading/wri ng files or exchanging informa on in an
efficient way. The stream module provides an API for implemen ng the stream interface. Examples
of the stream object in Node.js can be a request to an HTTP server and process.stdout are both
stream instances.
4. Explain crypto module in Node.js
The crypto module is used for encryp ng, decryp ng, or hashing any type of data. This encryp on
and decryp on basically help to secure and add a layer of authen ca on to the data. The main use
case of the crypto module is to convert the plain readable text to an encrypted format and decrypt it
when required.
5. What is callback hell?
Callback hell is an issue caused due to a nested callback. This causes the code to look like a pyramid
and makes it unable to read To overcome this situa on we use promises.
6. Explain the use of mers module in Node.js
The Timers module in Node.js contains various func ons that allow us to execute a block of code or a
func on a er a set period of me. The Timers module is global, we do not need to use require() to
import it.
It has the following methods:
 setTimeout() method
 setImmediate() method
 setInterval() method
7. Difference between setImmediate() and process.nextTick() methods
The process.nextTick() method is used to add a new callback func on at the start of the next event
queue. it is called before the event is processed. The setImmediate is called at the check phase of the
next event queue. It is created in the poll phase and is invoked during the check phase.
8. What is the difference between setTimeout() and setImmediate() method?
The setImmediate func on is used to execute a par cular script immediately whereas the
setTimeout func on is used to hold a func on and execute it a er a specified period of me.
9. What is the difference between spawn() and fork() method?
Both these methods are used to create new child processes the only difference between them is that
spawn() method creates a new func on that Node runs from the command line whereas fork()
func on creates an instance of the exis ng fork() method and creates mul ple workers to perform
on the same task.
10. Explain the use of passport module in Node.js
The passport module is used for adding authen ca on features to our website or web app. It
implements authen ca on measure which helps to perform sign-in opera ons.
11. What is fork in Node.js?
Fork is a method in Node.js that is used to create child processes. It helps to handle the increasing
workload. It creates a new instance of the engine which enables mul ple processes to run the code.
12. What are the three methods to avoid callback hell?
The three methods to avoid callback hell are:
 Using async/await()
 Using promises
 Using generators
13. What is body-parser in Node.js?
Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming
request bodies in a middleware before you handle it. It is an NPM module that processes data sent in
HTTP requests.
14. What is CORS in Node.js?
The word CORS stands for “Cross-Origin Resource Sharing”. Cross-Origin Resource Sharing is an HTTP-
header based mechanism implemented by the browser which allows a server or an API to indicate
any origins (different in terms of protocol, hostname, or port) other than its origin from which the
unknown origin gets permission to access and load resources. The cors package available in the npm
registry is used to tackle CORS errors in a Node.js applica on.
15. Explain the tls module in Node.js?
The tls module provides an implementa on of the Transport Layer Security (TLS) and Secure Socket
Layer (SSL) protocols that are built on top of OpenSSL. It helps to establish a secure connec on on
the network.
16. What is the use of url module in Node.js?
In Node.js url module is used to split the URL of the website into parts so that it becomes readable
and can be used in the different parts of the applica on. The parse() method is used with the url
module to separate the URL of the website into parts.
17. What is REST API?
Representa onal State Transfer (REST) is an architectural style that defines a set of constraints to be
used for crea ng web services. REST API is a way of accessing web services in a simple and flexible
way without having any processing. It works a er the request is sent from the client to the server in
the form of a web URL as HTTP GET or POST or PUT or DELETE request. A er that, a response comes
back from the server in the form of a resource which can be anything like HTML, XML, Image, or
JSON. But now JSON is the most popular format being used in Web Services.
18. Explain the engine Google uses for Node.js
The engine used by Google for Node.js is V8. It is one the fastest engine as it is wri en in C++. It
provides a run me environment for the execu on of JavaScript code. The best part is that the
JavaScript engine is completely independent of the browser in which it runs. It has a huge
community and is highly portable.
19. Name the tool used for wri ng consistent code
ESLint is a tool used in many IDEs to write consistent code styles. ESLint is wri en using Node.js to
provide a fast run me environment and easy installa on via npm.
20. What are the different kinds of HTTP requests?
The most commonly used HTTP requests are:
 GET: This request is used to read/retrieve data from a web server. GET returns an HTTP status
code of 200 (OK) if the data is successfully retrieved from the server.
 PUT: This request is used to modify the data on the server. It replaces the en re content at a
par cular loca on with data that is passed in the body payload. If there are no resources
that match the request, it will generate one.
 POST: This request is used to send data (file, form data, etc.) to the server. On successful
crea on, it returns an HTTP status code of 201.
 DELETE: This request is used to delete the data on the server at a specified loca on.

Node Interview Questions and Answers (2024) –


Advanced Level
1. What is a cluster in Node.js?
Due to a single thread in node.js, it handles memory more efficiently because there are no mul ple
threads due to which no thread management is needed. Now, to handle workload efficiently and to
take advantage of computer mul -core systems, cluster modules are created that provide us the way
to make child processes that run simultaneously with a single parent process.
2. Explain some of the cluster methods in Node.js
 Fork(): It creates a new child process from the master. The isMaster returns true if the
current process is master or else false.
 isWorker: It returns true if the current process is a worker or else false.
 process: It returns the child process which is global.
 send(): It sends a message from worker to master or vice versa.
 kill(): It is used to kill the current worker.
3. How to manage sessions in Node.js?
Session management can be done in node.js by using the express-session module. It helps in saving
the data in the key-value form. In this module, the session data is not saved in the cookie itself, just
the session ID.
4. Explain the types of streams in Node.js
Types of Stream:
 Readable stream: It is the stream from where you can receive and read the data in an
ordered fashion. However, you are not allowed to send anything. For example,
fs.createReadStream() lets us read the contents of a file.
 Writable stream: It is the stream where you can send data in an ordered fashion but you are
not allowed to receive it back. For example, fs.createWriteStream() lets us write data to a
file.
 Duplex stream: It is the stream that is both readable and writable. Thus you can send in and
receive data together. For example, net.Socket is a TCP socket.
 Transform stream: It is the stream that is used to modify the data or transform it as it is read.
The transform stream is basically a duplex in nature. For example, zlib.createGzip stream is
used to compress the data using gzip.
5. How can we implement authen ca on and authoriza on in Node.js?
Authen ca on is the process of verifying a user’s iden ty while authoriza on is determining what
ac ons can be performed. We use packages like Passport and JWT to implement authen ca on and
authoriza on.
6. Explain the packages used for file uploading in Node.js?
The package used for file uploading in Node.js is Multer. The file can be uploaded to the server using
this module. There are other modules in the market but Multer is very popular when it comes to file
uploading. Multer is a node.js middleware that is used for handling mul part/form-data, which is a
mostly used library for uploading files.
7. Explain the difference between Node.js and server-side scrip ng languages like Python
Node.js is the best choice for asynchronous programming Python is not the best choice for
asynchronous programming. Node.js is best suited for small projects to enable func onality that
needs less amount of scrip ng. Python is the best choice if you’re developing larger projects. Node.js
is best suited for memory-intensive ac vi es. Not recommended for memory-intensive ac vi es.
Node.js is a be er op on if your focus is exactly on web applica ons and website development. But,
Python is an all-rounder and can perform mul ple tasks like- web applica ons, integra on with back-
end applica ons, numerical computa ons, machine learning, and network programming. Node.js is
an ideal and vibrant pla orm available right now to deal with real- me web applica ons. Python
isn’t an ideal pla orm to deal with real- me web applica ons. The fastest speed and great
performance are largely due to Node.js being based on Chrome’s V8 which is a very fast and
powerful engine. Python is slower than Node.js, As Node.js is based on fast and powerful Chrome’s
V8 engine, Node.js u lizes JavaScript interpreter. Python using PyPy as Interpreter. In case of error
handling and debugging Python beats Node.js. Error handling in Python takes significantly very li le
me and debugging in Python is also very easy compared to Node.js.
8. How to handle database connec on in Node.js?
To handle database connec on in Node.js we use the driver for MySQL and libraries like Mongoose
for connec ng to the MongoDB database. These libraries provide methods to connect to the
database and execute queries.
9. How to read command line arguments in Node.js?
Command-line arguments (CLI) are strings of text used to pass addi onal informa on to a program
when an applica on is running through the command line interface of an opera ng system. We can
easily read these arguments by the global object in node i.e. process object. Below is the approach:
Step 1: Save a file as index.js and paste the below code inside the file.
 Javascript

let arguments = process.argv ;

console.log(arguments) ;

Step 2: Run the index.js file using the below command:


node index.js
10. Explain the Node.js redis module
Redis is an Open Source store for storing data structures. It is used in mul ple ways. It is used as a
database, cache, and message broker. It can store data structures such as strings, hashes, sets, sorted
sets, bitmaps, indexes, and streams. Redis is very useful for Node.js developers as it reduces the
cache size which makes the applica on more efficient. However, it is very easy to integrate Redis with
Node.js applica ons.
11. What is web socket?
Web Socket is a protocol that provides full-duplex (mul way) communica on i.e. allows
communica on in both direc ons simultaneously. It is a modern web technology in which there is a
con nuous connec on between the user’s browser (client) and the server. In this type of
communica on, between the web server and the web browser, both of them can send messages to
each other at any point in me. Tradi onally on the web, we had a request/response format where a
user sends an HTTP request and the server responds to that. This is s ll applicable in most cases,
especially those using RESTful API. But a need was felt for the server to also communicate with the
client, without ge ng polled(or requested) by the client. The server in itself should be able to send
informa on to the client or the browser. This is where Web Socket comes into the picture.
12. Explain the u l module in Node.js
The U l module in node.js provides access to various u lity func ons. There are various u lity
modules available in the node.js module library.
 OS Module: Opera ng System-based u lity modules for node.js are provided by the OS
module.
 Path Module: The path module in node.js is used for transforming and handling various file
paths.
 DNS Module: DNS Module enables us to use the underlying Opera ng System name
resolu on func onali es. The actual DNS lookup is also performed by the DNS Module.
 Net Module: Net Module in node.js is used for the crea on of both client and server. Similar
to DNS Module this module also provides an asynchronous network wrapper.
13. How to handle environment variables in Node.js?
We use process.env to handle environment variables in Node.js. We can specify environment
configura ons as well as keys in the .env file. To access the variable in the applica on, we use the
“process.env.VARIABLE_NAME” syntax. To use it we have to install the dotenv package using the
below command:
npm install dotenv
14. Explain DNS module in Node.js
DNS is a node module used to do name resolu on facility which is provided by the opera ng system
as well as used to do an actual DNS lookup. Its main advantage is that there is no need for
memorizing IP addresses – DNS servers provide a ni y solu on for conver ng domain or subdomain
names to IP addresses.
15. What are child processes in Node.js?
Usually, Node.js allows single-threaded, non-blocking performance but running a single thread in a
CPU cannot handle increasing workload hence the child_process module can be used to spawn child
processes. The child processes communicate with each other using a built-in messaging system.
16. How to validate data in Node.js?
Valida on in node.js can be easily done by using the express-validator module. This module is
popular for data valida on. There are other modules available in the market like hapi/joi, etc but
express-validator is widely used and popular among them.
17. What is the role of net module in Node.js?
The net module in Node.js is used to create TCP client and serve in Node.js. This module establishes
connec ons, handles incoming requests, and share data over the network.
18. What is tracing in Node.js?
The Tracing Objects are used for a set of categories to enable and disable the tracing. When tracing
events are created then tracing objects is disabled by calling tracing.enable() method and then
categories are added to the set of enabled trace and can be accessed by calling tracing.categories.
19. What is reactor pa ern in node.js?
Reactor Pa ern is used to avoid the blocking of the Input/Output opera ons. It provides us with a
handler that is associated with I/O opera ons. When the I/O requests are to be generated, they get
submi ed to a demul plexer, which handles concurrency in avoiding the blocking of the I/O mode
and collects the requests in the form of an event and queues those events.
20. How to Connect Node.js to a MongoDB Database?
To connect to MongoDB database write the following code a er installing the Mongoose package
 Javascript

const mongoose = require("mongoose");

mongoose.connect("DATABASE_URL_HERE", {
useNewUrlParser: true,
useUnifiedTopology: true
});

You might also like