66 MERN Stack Interview Questions (ANSWERED) To Nail Your Next Tech Interview - FullStack - Cafe
66 MERN Stack Interview Questions (ANSWERED) To Nail Your Next Tech Interview - FullStack - Cafe
MERN stands for MongoDB, Express, React, Node, after the four key technologies that make up the stack. MERN is one of
several variations of the MEAN stack (MongoDB Express Angular Node), where the traditional Angular.js frontend
framework is replaced with React.js. Follow along and check 66 most common MERN Stack Interview Questions you are
most likely will be asked on your next MERN Developer interview.
React
Q1: How does React work? Entry 130
Answer
React creates a virtual DOM. When state changes in a component it firstly runs a "diffing" algorithm, which identifies what has changed in the virtual DOM. The second step is
reconciliation, where it updates the DOM with the results of diff.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/Pau1fitz
React
Q2: What are React Hooks? Entry 130
Answer
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. With Hooks, you can extract stateful logic from a component so it
can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many
components or with the community.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: reactjs.org
React
Q3: What are props in React? Entry 130
Answer
Props are inputs to a React component. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention
similar to HTML-tag attributes. i.e, They are data passed down from a parent component to a child component.
This reactProp (or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created
using React library.
props.reactProp;
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
React
Q4: What are the advantages of ReactJS? Entry 130
Answer
Below are the advantages of ReactJS:
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
React
Q5: How is React different from AngularJS (1.x)? Junior 130
Answer
For example, AngularJS (1.x) approaches building an application by extending HTML markup and injecting various constructs (e.g. Directives, Controllers, Services) at runtime. As a
result, AngularJS is very opinionated about the greater architecture of your application — these abstractions are certainly useful in some cases, but they come at the cost of flexibility.
By contrast, React focuses exclusively on the creation of components, and has few (if any) opinions about an application’s architecture. This allows a developer an incredible amount
of flexibility in choosing the architecture they deem “best” — though it also places the responsibility of choosing (or building) those parts on the developer.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: codementor.io
Dynamic Programming 12
MongoDB
Q6: What Is Replication In MongoDB? Junior 77
Answer
Replication is the process of synchronizing data across multiple servers.
Replication provides redundancy and increases data availability. With multiple copies of data on different database servers, replication provides a level of fault tolerance against the
loss of a single database server.
In some cases, replication can provide increased read capacity as clients can send read operations to different servers. Maintaining copies of data in different data centres can
increase data locality and availability for distributed applications. You can also maintain additional copies for dedicated purposes, such as disaster recovery, reporting, or backup.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: www.mongodb.com
React
Q7: What are Higher-Order Components (HOC) in React? Junior 130
Answer
A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature We
call them as “pure’ components” because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
React
Q8: What are advantages of using React Hooks? Junior 130
Answer
Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render
props. Hooks allow to easily manipulate the state of our functional component without needing to convert them into class components.
Hooks don’t work inside classes (because they let you use React without classes). By using them, we can totally avoid using lifecycle methods, such
as componentDidMount , componentDidUpdate , componentWillUnmount . Instead, we will use built-in hooks like useEffect .
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: hackernoon.com
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
Junior React
Q9: What are the limitations of React? 130
Answer
Below are the list of limitations:
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
Objective-C 43 iOS 36
Junior React
Q10: What are the differences between a Class component and Functional 130
component?
Answer
Class Components
Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.
Class components extend from React.Component.
In here you have to use this keyword to access the props and functions that you declare inside the class components.
Functional Components
Junior Node.js
Q11: What are the key features of Node.js? 126
Answer
Let’s look at some of the key features of Node.js.
Asynchronous event driven IO helps concurrent request handling – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some
Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous
requests.
Fast in Code execution – Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which
makes the runtime engine much faster and hence processing of requests within Node.js also become faster.
Single Threaded but Highly Scalable – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately.
However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single
thread that provides service to much larger numbers of such requests.
Node.js library uses JavaScript – This is another important aspect of Node.js from the developer’s point of view. The majority of developers are already well-versed in
JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.
There is an Active and vibrant community for the Node.js framework – The active community always keeps the framework updated with the latest trends in the web
development.
No Buffering – Node.js applications never buffer any data. They simply output the data in chunks.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: techbeamers.com
Node.js
Q12: What do you mean by Asynchronous API? Junior 126
Answer
All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after
calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: tutorialspoint.com
Node.js
Q13: What is Callback Hell and what is the main cause of it? Junior 126
Answer
Asynchronous JavaScript, or JavaScript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
See the pyramid shape and all the }) at the end? This is affectionately known as callback hell.
The cause of callback hell is when people try to write JavaScript in a way where execution happens visually from top to bottom. Lots of people make this mistake! In other
languages like C, Ruby or Python there is the expectation that whatever happens on line 1 will finish before the code on line 2 starts running and so on down the file.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: callbackhell.com
React Hooks 46
React
Q14: What is Reconciliation in ReactJS? Junior 130
Answer
When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one.
When they are not equal, React will update the DOM. This process is called reconciliation.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
MongoDB
Q15: What is Sharding in MongoDB? Junior 77
Answer
Sharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.
MongoDB supports horizontal scaling through sharding. MongoDB shards data at the collection level, distributing the collection data across the shards in the cluster.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: www.mongodb.com
ASP.NET Web API 33 Web Security 58 Xamarin 83 HTML5 55 CSS 50 Vue.js 41 React 130
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
Node.js
Q16: What is the difference between returning a callback and just calling a Junior 126
callback?
Answer
return callback();
//some more lines of code; - won't be executed
callback();
//some more lines of code; - will be executed
Of course returning will help the context calling async function get the value returned by callback.
function do2(callback) {
log.trace('Execute function: do2');
return callback('do2 callback param');
}
log.trace(`print ${do2Result}`);
Output:
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: stackoverflow.com
Junior MongoDB
Q17: When should we embed one document within another in MongoDB? 77
Answer
You should consider embedded documents (subdocuments) for:
When the relationship is one-to-few (not many, not unlimited). For unlimited use case, you should start considering separating subdocuments into another collection.
When retrieval is likely to happen together, that will improve performance
When updates are likely to happen at the same time. Although starting from MongoDB 4.0, you can use multi-documents transactions, a single document transaction would be
more performant
When the field is rarely updated
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
GraphQL 25
MongoDB
Q18: Does Mongodb support Foreign Key constraints? Mid 77
Answer
No.
One of the great things about relational database is that it is really good at keeping the data consistent within the database. One of the ways it does that is by using foreign keys. A
foreign key constraint is that let's say there's a table with some column which will have a foreign key column with values from another table's column.
In MongoDB , there's no guarantee that foreign keys will be preserved. It's upto the programmer to make sure that the data is consistent in that manner. Constraints can not be
enforced by MongoDB either. It can't even enforce a specific type for a field, due to the schemaless nature of MongoDB.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
MongoDB
Q19: Explain advantages of BSON over JSON in MongoDB? Mid 77
Answer
BSON is designed to be efficient in space, but in some cases is not much more efficient than JSON. In some cases BSON uses even more space than JSON. The reason for
this is another of the BSON design goals: traversability. BSON adds some "extra" information to documents, like length of strings and subobjects. This makes traversal faster.
BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses
more space than JSON for small integers, but is much faster to parse.
In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
React
Q20: Given the React code defined above, can you identify two problems? Mid 130
Problem
Take a look at the code below:
componentDidMount() {
this.refs.myComponentDiv.addEventListener('click', this.clickHandler);
}
componentWillUnmount() {
this.refs.myComponentDiv.removeEventListener('click', this.clickHandler);
}
clickHandler() {
this.setState({
clicks: this.clicks + 1
});
}
render() {
let children = this.props.children;
return (
<div className="my-component" ref="myComponentDiv">
<h2>My Component ({this.state.clicks} clicks})</h2>
<h3>{this.props.headerText}</h3>
{children}
</div>
);
}
}
Given the code defined above, can you identify two problems?
Answer
1. The constructor does not pass its props to the super class. It should include the following line:
constructor(props) {
super(props);
// ...
}
2. The event listener (when assigned via addEventListener() ) is not properly scoped because ES2015 doesn’t provide autobinding. Therefore the developer can re-
assign clickHandler in the constructor to include the correct binding to this:
constructor(props) {
super(props);
this.clickHandler = this.clickHandler.bind(this);
// ...
}
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: codementor.io
MongoDB
Q21: How can you achieve Transaction in MongoDB? Mid 77
Answer
In MongoDB, an operation on a single document is atomic.
Because you can use embedded documents and arrays to capture relationships between data in a single document structure instead of normalizing across multiple documents and
collections, this single-document atomicity obviates the need for multi-document transactions for many practical use cases.
For situations that require atomicity of reads and writes to multiple documents (in single or multiple collections), MongoDB supports multi-document (distributed) transactions.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: www.mongodb.com
Entity Framework 57
Node.js
Q22: How does Node.js handle Child Threads? Mid 126
Answer
Node.js, in its essence, is a single thread process. It does not expose child threads and thread management methods to the developer. js does spawn child threads for certain
tasks such as asynchronous I/O, but these run behind the scenes and do not execute any application JavaScript code, nor block the main event loop.
If threading support is desired in a Node.js application, there are tools available to enable it, such as the ChildProcess module.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: medium.com
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
Mid Node.js
Q23: How does concurrency work in Node.js? 126
Answer
The thing with node.js is that everything runs concurrently, except for your code.
So, what that means is that there are actually lots of threads running inside Node.js virtual machine (or a thread pool if you wish), and those threads are utilized whenever you call an
async function like performing i/o operations on files, accessing databases, requesting urls, etc.
However, for your code, there is only a single thread, and it processes events from an event queue. So, when you register a callback its reference is actually passed to the
background worker thread, and once the async operation is done, new event is added to the event-queue with that callback
When Node gets I/O request it creates or uses a thread to perform that I/O operation and once the operation is done, it pushes the result to the event queue. On each such
event, event loop runs and checks the queue and if the execution stack of Node is empty then it adds the queue result to execution stack.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: stackoverflow.com
Mid Node.js
Q24: How to avoid Callback Hell in Node.js? 126
Answer
Node.js internally uses a single-threaded event loop to process queued events. But this approach may lead to blocking the entire process if there is a task running longer than
expected. Node.js addresses this problem by incorporating callbacks also known as higher-order functions. So whenever a long-running process finishes its execution, it triggers the
callback associated. Sometimes, it could lead to complex and unreadable code. More the no. of callbacks, longer the chain of returning callbacks would be.
There are four solutions which can address the callback hell problem:
Make your program modular - It proposes to split the logic into smaller modules. And then join them together from the main module to achieve the desired result.
Use async/await mechanism - Async /await is another alternative for consuming promises, and it was implemented in ES8, or ES2017. Async/await is a new way of writing
promises that are based on asynchronous code but make asynchronous code look and behave more like synchronous code.
Use promises mechanism - Promises give an alternate way to write async code. They either return the result of execution or the error/exception. Implementing promises
requires the use of .then() function which waits for the promise object to return. It takes two optional arguments, both functions. Depending on the state of the promise only
one of them will get called. The first function call proceeds if the promise gets fulfilled. However, if the promise gets rejected, then the second function will get called.
Use generators - Generators are lightweight routines, they make a function wait and resume via the yield keyword. Generator functions uses a special syntax function* () .
They can also suspend and resume asynchronous operations using constructs such as promises or thunks and turn a synchronous code into asynchronous.
function* HelloGen() {
yield 100;
yield 400;
}
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: techbeamers.com
Mid MongoDB
Q25: How to query MongoDB with like ? 77
Answer
I want to query something as SQL's like query:
select *
from users
where name like '%m%'
Answer
db.users.find({"name": /.*m.*/})
// or
db.users.find({"name": /m/})
You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to Regexp's '.*' ), not something that has "m" anchored to the beginning of the string.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
Career 1
Node.js
Q26: Rewrite promise-based Node.js applications to async/await Mid 126
Problem
Rewrite this code to async/await :
function asyncTask() {
return functionA()
.then((valueA) => functionB(valueA))
.then((valueB) => functionC(valueB))
.then((valueC) => functionD(valueC))
.catch((err) => logger.error(err))
}
Answer
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: stackoverflow.com
React
Q27: What are Pure Components? Mid 130
Answer
PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for you.
When props or state changes, PureComponent will do a shallow comparison on both props and state. Component, on the other hand, won’t compare current props and state to next
out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
React
Q28: What is prop drilling and how can you avoid it? Mid 130
Answer
When building a React application, there is often the need for a deeply nested component to use data provided by another component that is much higher in the hierarchy. The
simplest approach is to simply pass a prop from each component to the next in the hierarchy from the source component to the deeply nested component. This is called prop
drilling.
The primary disadvantage of prop drilling is that components that should not otherwise be aware of the data become unnecessarily complicated and are harder to maintain.
To avoid prop drilling, a common approach is to use React context. This allows a Provider component that supplies data to be defined, and allows nested components to consume
context data via either a Consumer component or a useContext hook.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: toptal.com
React
Q29: What is Key and benefit of using it in lists? Mid 130
Answer
A key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.
For example, most often we use IDs from your data as keys
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
Note:
1. We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state
2. If you extract list item as separate component then apply keys on list component instead li tag.
There will be a warning in the console if the key is not present on list items.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
FULL-STACK, WEB & MOBILE ALGORITHMS & DATA STRUCTURES SYS
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
Mid Node.js
Q30: What is stream and what are types of streams available in Node.js? 126
Answer
A stream is an abstract interface for working with streaming data in Node.js.
Streams basically provide two major advantages over using other data handling methods:
Memory efficiency: you don't need to load large amounts of data in memory before you are able to process it
Time efficiency: it takes way less time to start processing data, since you can start processing as soon as you have it, rather than waiting till the whole data payload is available
1. Writable: streams to which we can write data. For example, fs.createWriteStream() lets us write data to a file using streams.
2. Readable: streams from which data can be read. For example: fs.createReadStream() lets us read the contents of a file.
3. Duplex: streams that are both Readable and Writable. For example, net.Socket
4. Transform: streams that can modify or transform the data as it is written and read. For example, in the instance of file-compression, you can write compressed data and read
decompressed data to and from a file.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: nodesource.com
Mid Node.js
Q31: What is a Blocking Code in Node.js? 126
Answer
A blocking call causes results to be returned synchronously.
Performing a blocking system call causes the process to enter the blocked state. Control is let back to the process only after the I/O event that is being waited upon occurs.
const fs = require("fs");
const contents = fs.readFileSync("file.txt", "utf8");
// this line is not reached until the read results are in
console.log(contents);
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: bytearcher.com
Mid MongoDB
Q32: What is an Aggregation Pipeline in MongoDB? 77
Answer
Aggregation operations process multiple documents and return computed results. You can use aggregation operations to:
MongoDB provides aggregation operations through aggregation pipelines — a series of operations that process data documents sequentially. An aggregation pipeline consists of one
or more stages that process documents:
Each stage performs an operation on the input documents. For example, a stage can filter documents, group documents, and calculate values.
The documents that are output from a stage are passed to the next stage.
An aggregation pipeline can return results for groups of documents. For example, return the total, average, maximum, and minimum values.
Consider:
db.orders.aggregate([
// Stage 1: Filter pizza order documents by pizza size
{
$match: { size: "medium" }
},
// Stage 2: Group remaining documents by pizza name and calculate total quantity
{
$group: { _id: "$name", totalQuantity: { $sum: "$quantity" } }
}
])
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: www.digitalocean.com
React
Q33: What is the difference between ShadowDOM and VirtualDOM? Mid 130
Answer
Virtual DOM
Virtual DOM is about avoiding unnecessary changes to the DOM, which are expensive performance-wise, because changes to the DOM usually cause re-rendering of the page.
Virtual DOM also allows to collect several changes to be applied at once, so not every single change causes a re-render, but instead re-rendering only happens once after a set of
changes was applied to the DOM.
Shadow DOM
Shadow dom is mostly about encapsulation of the implementation. A single custom element can implement more-or-less complex logic combined with more-or-less complex DOM.
An entire web application of arbitrary complexity can be added to a page by an import and <body><my-app></my-app> but also simpler reusable and composable components can be
implemented as custom elements where the internal representation is hidden in the shadow DOM like <date-picker></date-picker> .
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: stackoverflow.com
Node.js
Q34: What's the Event Loop? Mid 126
Answer
The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel
whenever possible.
Every I/O requires a callback - once they are done they are pushed onto the event loop for execution. Since most modern kernels are multi-threaded, they can handle multiple
operations executing in the background. When one of these operations completes, the kernel tells Node.js so that the appropriate callback may be added to the poll queue to
eventually be executed.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: blog.risingstack.com
Mid React
Q35: What's the difference between useRef and createRef ? 130
Answer
The difference is:
createRef will always create a new ref. In a class-based component, you would typically put the ref in an instance property during construction (e.g. this.input = createRef() ).
You don't have this option in a function component.
useRef takes care of returning the same ref each time as on the initial rendering.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: reactjs.org
React Hooks
Q36: Do Hooks replace render props and higher-order components (HOC)? Senior 46
Answer
Often, render props and higher-order components render only a single child. React team thinks Hooks are a simpler way to serve this use case.
There is still a place for both patterns (for example, a virtual scroller component might have a renderItem prop, or a visual container component might have its own DOM
structure). But in most cases, Hooks will be sufficient and can help reduce nesting in your tree.
Having Tech or Coding Interview? Check 👉 46 React Hooks Interview Questions Source: reactjs.org
iOS 36 Dependency Injection 17 Design Patterns 68 Entity Framework 57 Java 165 Azure 59
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
Senior MongoDB
Q37: How replication works in MongoDB? 77
Answer
A replica set consists of a primary node and a secondary node too. With the help of a replica set, all the data from primary node to the secondary node replicates. Replication is a
process of synchronizing the data. Replication provides redundancy and it also increases the availability of data with the help of multiple copies of data on the different database
server. It also protects the database from the loss of a single server.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: interviewbubble.com
MongoDB 77
React
Q38: How to apply validation on props in ReactJS? Senior 130
Answer
When the application is running in development mode, React will automatically check for all props that we set on components to make sure they must right correct and right data
type. For incorrect type, it will generate warning messages in the console for development mode whereas it is disabled in production mode due performance impact. The mandatory
prop is defined with isRequired.
1. React.PropTypes.string
2. React.PropTypes.number
3. React.PropTypes.func
4. React.PropTypes.node
5. React.PropTypes.bool
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
};
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: github.com/sudheerj
Senior Node.js
Q39: Is Node.js entirely based on a single-thread? 126
Answer
Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes
use of events and callbacks to handle a large no. of requests asynchronously.
Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome
v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.
To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards
to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: techbeamers.com
Senior Node.js
Q40: Is it possible to use Class in Node.js? 126
Answer
With ES6, you are able to make "actual" classes just like this:
class Animal {
constructor(name) {
this.name = name;
}
print() {
console.log('Name is :' + this.name);
}
}
};
Once imported into another module, then you can treat it as if it were defined in that file:
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: stackoverflow.com
MongoDB
Q41: Update MongoDB field using value of another field Senior 77
Answer
Consider SQL command:
In Mongo, is it possible to update the value of a field using the value from another field?
Answer
You cannot refer to the document itself in an update (yet). You'll need to iterate through the documents and update each document using a function like:
db.person.find().snapshot().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
Angular 120
Senior React
Q42: What is the purpose of super(props) ? 130
Answer
When you pass props to super , the props get assigned to this . Take a look at the following scenario:
constructor(props) {
super();
console.log(this.props) //undefined
}
constructor(props) {
super(props);
console.log(this.props) //props will get logged.
}
Note that passing or not passing props to super has no effect on later uses of this.props outside constructor . That is render , shouldComponentUpdate , or event
handlers always have access to it.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: stackoverflow.com
Senior Node.js
Q43: When not to use Node.js? 126
Answer
We can use Node.js for a variety of applications. But it is a single threaded framework, so we should not use it for cases
where the application requires long processing time (If the server is doing some calculation) ,
it won’t be able to process any other requests. Hence, Node.js is best when processing needs less dedicated CPU time.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: techbeamers.com
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
MongoDB
Q44: When to use Redis or MongoDB? Senior 77
Answer
Use MongoDB if you don't know yet how you're going to query your data or what schema to stick with. MongoDB is suited for Hackathons, startups or every time you
don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational,
this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for
prototyping or trying things out. Its performance is not that great and can't be compared to Redis.
Use Redis in order to speed up your existing application. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-
value"-store).
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
MongoDB
Q45: Why is a Covered Query important? Senior 77
Answer
A covered query is a query that can be satisfied entirely using an index and does not have to examine any documents. Because the index contains all fields required by the query,
MongoDB can both match the query conditions and return the results using only the index.
Querying only the index can be much faster than querying documents outside of the index. Index keys are typically smaller than the documents they catalog, and indexes are
typically available in RAM or located sequentially on disk.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: www.mongodb.com
LINQ 38
React
Q46: Why would you need to bind event handlers to this ? Senior 130
Answer
Binding is not something that is specifc to React, but rather how this works in Javascript. When you define a component using an ES6 class, a common pattern is for an event
handler to be a method on the class. In JavaScript, class methods are not bound by default. If you forget to bind this.someEventHandler and pass it to onChange , this will be
undefined when the function is actually called.
Generally, if you refer to a method without () after it, such as onChange={this.someEventHandler} , you should bind that method.
Having Tech or Coding Interview? Check 👉 130 React Interview Questions Source: stackoverflow.com
Node.js
Q47: Explain the result of this code execution Expert 126
Problem
Explain the result of this code execution
crazy.on('event1', function () {
console.log('event1 fired!');
setImmediate(function () {
crazy.emit('event2');
});
});
crazy.on('event2', function () {
console.log('event2 fired!');
setImmediate(function () {
crazy.emit('event3');
});
});
crazy.on('event3', function () {
console.log('event3 fired!');
setImmediate(function () {
crazy.emit('event1');
});
});
crazy.emit('event1');
Answer
Shortly - the app will be run infinitely. Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the event loop.
Without setImmidiate all callbacks are executed in a synchronous manner. With setImmidiate each call back executed as a part of next event loop iteration so no recursion/stuck
occurs.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: codementor.io
Expert Node.js
Q48: How V8 compiles JavaScript code? 126
Answer
V8 has two compilers:
A “Full” Compiler that can generate good code for any JavaScript: good but not great JIT code. The goal of this compiler is to generate code quickly. To achieve its goal, it
doesn’t do any type analysis and doesn’t know anything about types. Instead, it uses an Inline Caches or “IC” strategy to refine knowledge about types while the program runs.
IC is very efficient and brings about 20 times speed improvment.
An Optimizing Compiler that produces great code for most of the JavaScript language. It comes later and re-compiles hot functions. The optimizing compiler takes types from
the Inline Cache and make decisions about how to optimize the code better. However, some language features are not supported yet like try/catch blocks for instance. (The
workaround for try/catch blocks is to write the “non stable” code in a function and call the function in the try block)
V8 also supports de-optimization: the optimizing compiler makes optimistic assumptions from the Inline Cache about the different types, de-optimization comes if these assumptions
are invalid. For example, if a hidden class generated was not the one expected, V8 throws away the optimized code and comes back to the Full Compiler to get types again from the
Inline Cache. This process is slow and should be avoided by trying to not change functions after they are optimized.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: thibaultlaurens.github.io
Node.js
Q49: How does libuv work under the hood? Expert 126
Answer
There is only one thread that executes JavaScript code and this is the thread where the event loop is running provided by libuv. The execution of callbacks (know that every userland
code in a running Node.js application is a callback) is done by the event loop.
Libuv by default creates a thread pool with four threads to offload asynchronous work to. Today’s operating systems already provide asynchronous interfaces for many I/O tasks (e.g.
AIO on Linux). Whenever possible, libuv will use those asynchronous interfaces, avoiding usage of the thread pool.
The event loop as a process is a set of phases with specific tasks that are processed in a round-robin manner. Each phase has a FIFO queue of callbacks to execute. While each
phase is special in its own way, generally, when the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase's
queue until the queue has been exhausted or the maximum number of callbacks has executed. When the queue has been exhausted or the callback limit is reached, the event loop
will move to the next phase, and so on.
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: nodejs.org
PWA 22
MongoDB
Q50: How to find document with array that contains a specific value? Expert 77
Problem
You have this schema:
person = {
name : String,
favoriteFoods : Array
}
where the favoriteFoods array is populated with strings. How can I find all persons that have sushi as their favorite food using MongoDB?
Answer
Consider:
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: docs.mongodb.com
🤖 Having Machine Learning & DS Interview? Check MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS
Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers
Node.js
Q51: Rewrite the code sample without try/catch block Expert 126
Problem
Consider the code:
Answer
Having Tech or Coding Interview? Check 👉 126 Node.js Interview Questions Source: medium.com
MongoDB
Q52: Where does MongoDB stand in the CAP theorem? Expert 77
Answer
MongoDB is strongly consistent by default - if you do a write and then do a read, assuming the write was successful you will always be able to read the result of the write you just
read. This is because MongoDB is a single-master system and all reads go to the primary by default.
On the other hand you can't just say that MongoDB is CP/AP/CA, because it actually is a trade-off between C, A and P, depending on both database/driver configuration and type of
disaster: here's a visual recap, and below a more detailed explanation.
Consistency - MongoDB is strongly consistent when you use a single connection or the correct Write/Read Concern Level (Which will cost you execution speed). As soon as you
don't meet those conditions (especially when you are reading from a secondary-replica) MongoDB becomes Eventually Consistent.
Availability - MongoDB gets high availability through Replica-Sets. As soon as the primary goes down or gets unavailable else, then the secondaries will determine a new primary to
become available again. There is an disadvantage to this: Every write that was performed by the old primary, but not synchronized to the secondaries will be rolled back and saved to
a rollback-file, as soon as it reconnects to the set(the old primary is a secondary now). So in this case some consistency is sacrificed for the sake of availability.
Partition Tolerance - Through the use of said Replica-Sets MongoDB also achieves the partition tolerance: As long as more than half of the servers of a Replica-Set is connected to
each other, a new primary can be chosen. Why? To ensure two separated networks can not both choose a new primary. When not enough secondaries are connected to each other
you can still read from them (but consistency is not ensured), but not write. The set is practically unavailable for the sake of consistency.
Having Tech or Coding Interview? Check 👉 77 MongoDB Interview Questions Source: stackoverflow.com
Expert Node.js
Q53: Why should you separate Express app and server? 126
Answer
Keeping the API declaration separated from the network related configuration (port, protocol, etc) allows testing the API in-process, without performing network calls, with all the
benefits that it brings to the table: fast testing execution and getting coverage metrics of the code. It also allows deploying the same API under flexible and different network
conditions. Bonus: better separation of concerns and cleaner code.
/**
* Get port from environment and store in Express.
*/