answer
answer
Node JS
1. What is Node.js? Where can you use it?
2. Why use Node.js?
3. How does Node.js work?
4. Why is Node.js Single-threaded?
5. If Node.js is single-threaded, then how does it handle concurrency?
6. Explain callback in Node.js.
7. What are the advantages of using promises instead of callbacks?
8. How would you define the term I/O?
9. How is Node.js most frequently used?
10. Explain the difference between frontend and backend development?
11. What is NPM?
12. What are the modules in Node.js?
13. What is the purpose of the module .Exports?
14. What is the difference between Angular and Node.js?
15. Which database is more popularly used with Node.js?
16. What are some of the most commonly used libraries in Node.js?
17. What are the pros and cons of Node.js?
18. What is the command used to import external libraries?
19. What does event-driven programming mean?
20. What is an Event Loop in Node.js?
21. What is an EventEmitter in Node.js?
22. What are the two types of API functions in Node.js?
23. What is the package.json file?
24. How would you use a URL module in Node.js?
25. What is the Express.js package?
26. How do you create a simple Express.js application?
27. What are streams in Node.js?
28. How do you install, update, and delete a dependency?
29. How do you create a simple server in Node.js that returns Hello World?
30. Explain asynchronous and non-blocking APIs in Node.js
31. How do we implement async in Node.js?
32. What is a callback function in Node.js?
33. What is REPL in Node.js?
34. What is the control flow function?
35. How does control flow manage the function calls?
36. What is the difference between fork() and spawn() methods in Node.js?
37. What is the buffer class in Node.js?
38. What is piping in Node.js?
39. What are some of the flags used in the read/write operations in files?
40. How do you open a file in Node.js?
41. What is callback hell?
42. What is a reactor pattern in Node.js?
43. What is a test pyramid in Node.js?
Logical Questions
Logical Program:
1. WAP to Swapping of two variables using third variable.
2. WAP to Swap of two variables using without third variable.
3. WAP to find Rupees and Paisa from any rupees of 12.50
Input:
12.50
Output:
12 Rupees
50 Paisa
4. WAP to print sum of Digit of given number?
Input:
768
Output:
21
5. WAP to Print sum of first and last digit of given number?
Input:
768
Output:
15
Input :
8983
Output:
11
1
21
321
4321
54321
5
54
543
5432
54321
5
45
345
2345
12345
1
23
456
7 8 9 10
1112131415
1
23
46
7
10
1112131415
0
01
010
0101
01010
1
10
101
1010
10101
1
01
010
1010
10101
1
00
111
0000
11111
0
11
000
1111
00000
1
11
121
1331
14641
*
**
***
****
*****
1
**
123
****
12345
54321
5432
543
54
5
12345
1234
123
12
1
1
121
12321
1234321
123454321
1112131415
*
***
*****
*******
********
1415
*
*
**
**
***
***
****
****
*****
*****
****
****
***
***
**
**
*
*
16. WAP to find sum of all array values and find Average of array
17. WAP to find maximum and minimum values in Array
18. WAP to make Reverse array of given array
19. WAP to check Array is Palindrome or not
20. WAP to sort the array in ascending order and descending order using bubble sort.
21. WAP to insert one element on particular position in given array
22. WAP to delete one element in given array using position and Values
23. WAP to delete duplicate values in given array
OR
WAP to find unique values in given array
javascript
Sure! Below are the answers to all the questions you’ve listed. If you’d like them in a PDF format, you can
copy the content below into a document and save it as a PDF.
---
---
Example:
‘‘‘javascript
console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 10;
‘‘‘
---
Example:
‘‘‘javascript
function test() {
debugger; // Execution stops here
console.log("Hello World");
}
test();
‘‘‘
---
Example:
‘‘‘javascript
5 == ’5’; // true
5 === ’5’; // false
‘‘‘
---
let b = 10;
let b = 20; // SyntaxError
‘‘‘
---
Example:
‘‘‘javascript
’5’ + 2; // ’52’ (string)
’5’ - 2; // 3 (number)
‘‘‘
---
---
Example:
‘‘‘javascript
0 / 0; // NaN
"abc" * 2; // NaN
‘‘‘
---
---
Example:
‘‘‘javascript
(function() {
console.log("Executed immediately!");
})();
‘‘‘
---
### 11. **What do you mean by strict mode in JavaScript and characteristics of JavaScript strict-mode?**
Strict mode is a stricter variant of JavaScript that makes error handling more stringent and helps avoid
common pitfalls.
Characteristics:
- Prevents undeclared variables.
- Eliminates ‘this‘ referring to the global object.
- Prohibits using ‘with‘ statements.
---
Example:
‘‘‘javascript
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // map is a higher-order function
‘‘‘
---
---
Example:
‘‘‘javascript
(function() {
console.log("Self Invoking Function!");
})();
‘‘‘
---
Example:
‘‘‘javascript
function greet(name) {
console.log(‘Hello, ${name}‘);
}
---
### 16. **What is the difference between ‘exec()‘ and ‘test()‘ methods in JavaScript?**
- **‘exec()‘**: Executes a regular expression on a string and returns an array of matches.
- **‘test()‘**: Tests whether a regular expression matches a string, returning ‘true‘ or ‘false‘.
---
Example:
‘‘‘javascript
function add(a) {
return function(b) {
return a + b;
};
}
const add5 = add(5);
console.log(add5(3)); // 8
‘‘‘
---
---
---
Example:
‘‘‘javascript
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}
---
---
---
---
---
---
---
---
### 28
. **What is DOM?**
The **Document Object Model (DOM)** represents the HTML document as a tree structure, where each
element is a node that can be manipulated using JavaScript.
---
### 29. **Which method is used to retrieve a character from a certain index?**
The ‘charAt()‘ method is used to retrieve the character at a specific index in a string.
Example:
‘‘‘javascript
let str = ’Hello’;
console.log(str.charAt(1)); // ’e’
‘‘‘
---
---
### 31. **What is the distinction between client-side and server-side JavaScript?**
- **Client-side JavaScript** runs in the user’s browser, handling tasks like form validation, animations, and
AJAX requests.
- **Server-side JavaScript** runs on a server, handling tasks like managing databases, user
authentication, and serving web pages (e.g., Node.js).
---
Example:
‘‘‘javascript
const sum = (a, b) => a + b;
‘‘‘
---
---
### 34. **Differences between declaring variables using ‘var‘, ‘let‘, and ‘const‘.**
- **‘var‘**: Function-scoped, can be redeclared, and initialized.
- **‘let‘**: Block-scoped, can be reassigned but not redeclared in the same scope.
- **‘const‘**: Block-scoped, cannot be reassigned or redeclared.
---
---
### 36. **In JavaScript, how many different methods can you make an object?**
Objects can be created in JavaScript using:
- Object literals
- ‘Object.create()‘
- Constructor functions
- ‘class‘ syntax (ES6)
---
---
---
---
---
---
Example:
‘‘‘javascript
const person = { name: ’John’, age: 30 };
const { name, age } = person;
‘‘‘
---
---
---
---
---
### 48. **Difference between Async/Await and Generators usage to achieve the same functionality.**
Both **‘async/await‘** and **generators** can handle asynchronous code, but ‘async/await‘ provides a
more modern and readable syntax, while generators allow more control over the asynchronous flow.
---
---
---
### 51. **What has to be done in order to put Lexical Scoping into practice?**
Lexical scoping means that variables are scoped to the block where they are defined. To use lexical
scoping effectively, ensure functions access variables from their containing scope.
---
### 58. **Write a function that performs binary search on a sorted array.**
‘‘‘javascript
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
---
### 59. **Implement a function that returns an updated array with ‘r‘ right rotations on an array of
integers.**
‘‘‘javascript
function rotateArray(arr, r) {
r = r % arr.length; // Ensure the number of rotations is within array length
return arr.slice(-r).concat(arr.slice(0, arr.length - r));
}
‘‘‘
---
### 60. **Write the code for dynamically inserting new components.**
‘‘‘javascript
const newElement = document.createElement(’div’);
newElement.textContent = ’New Component’;
document.body.appendChild(newElement);
‘‘‘
---
### 61. **Write the code given If two strings are anagrams of one another, then return true.**
‘‘‘javascript
function areAnagrams(str1, str2) {
return str1.split(’’).sort().join(’’) === str2.split(’’).sort().join(’’);
}
‘‘‘
---
---
### 63. **In JavaScript, how do you turn an Object into an Array ‘[]‘?**
You can use ‘Object.values()‘, ‘Object.keys()‘, or ‘Object.entries()‘ to convert an object into an array.
Example:
‘‘‘javascript
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj); // [1, 2, 3]
‘‘‘
---
node js
Here are the answers to the Node.js-related questions you provided. You can easily copy and save this
text into a ‘.txt‘ file or use it for any other purpose.
---
---
---
---
---
---
---
---
---
---
### 10. **Explain the difference between frontend and backend development?**
Frontend development refers to the part of the application that the user interacts with, usually in the
browser (HTML, CSS, JavaScript). Backend development involves the server-side logic, databases, and
APIs that support the frontend.
---
---
---
---
---
---
### 16. **What are some of the most commonly used libraries in Node.js?**
Common libraries include:
- **Express.js** (Web framework)
- **Mongoose** (MongoDB ODM)
- **Socket.io** (Real-time communication)
- **Lodash** (Utility library)
---
**Cons**:
- Not suitable for CPU-heavy tasks
- Callback hell in complex asynchronous code
- Limited support for multi-threading
---
---
---
---
---
### 22. **What are the two types of API functions in Node.js?**
1. **Asynchronous functions**: Non-blocking operations (e.g., ‘fs.readFile()‘).
2. **Synchronous functions**: Blocking operations that return results immediately (e.g.,
‘fs.readFileSync()‘).
---
---
---
---
---
---
### 29. **How do you create a simple server in Node.js that returns Hello World?**
‘‘‘javascript
const http = require(’http’);
const server = http.createServer((req, res) => {
res.writeHead(200, { ’Content-Type’: ’text/plain’ });
res.end(’Hello World’);
});
server.listen(3000, () => console.log(’Server running on port 3000’));
‘‘‘
---
---
---
---
---
### 35. **How does control flow manage the function calls?**
Control flow in Node.js allows asynchronous operations to be scheduled in the event loop. It helps
manage when functions are executed and ensures non-blocking behavior.
---
### 36. **What is the difference between fork() and spawn() methods in Node.js?**
- ‘fork()‘: Used to spawn child processes with the ability to send and receive messages between parent
and child.
- ‘spawn()‘: Creates a new process and allows data exchange through streams, typically for external
processes.
---
---
---
---
### 40. **How do you open a file in Node.js?**
‘‘‘javascript
const fs = require(’fs’);
fs.open(’file.txt’, ’r’, (err, fd) => {
if (err) throw err;
console.log(’File opened:’, fd);
});
‘‘‘
---
---
---
---
### 44. **For Node.js, why does Google use the V8 engine?**
Google uses the V8 engine in Node.js because it is a highly optimized JavaScript engine that compiles
JavaScript to native machine code, providing high performance.
---
---
---
---
---
---
---
---
---
---
### 55. **List the two arguments that async first does the queue take as input.**
The two arguments are:
1. Callback function
2. Delay time (optional)
---
### 56. **What is the purpose of module.exports?**
‘module.exports‘ is used to expose functions, objects, or variables from a module, so other modules can
import and use them with ‘require()‘.
---
---
### 58. **What is the difference between asynchronous and synchronous functions?**
- **Asynchronous functions** run in the background and do not block the execution of other code.
- **Synchronous functions** block the execution until the task is completed.
---
### 59. **What are the asynchronous tasks that should occur in an event loop?**
Tasks like file I/O, network requests, database queries, and timers should be handled asynchronously in
the event loop.
---
---
---
---
---
---
### 65. **Can you access DOM in Node?**
No, Node.js does not have access to the DOM, as it is designed for server-side operations. The DOM is
only available in the browser.
---
### 66. **Why is Node.JS quickly gaining attention from JAVA programmers?**
Node.js is gaining attention because it allows JavaScript to be used across both the frontend and
backend, leading to a unified stack. It also offers high performance for web apps and APIs.
---
---
---
### 69. **How does Node.js overcome the problem of blocking I/O operations?**
Node.js uses an event loop and asynchronous callbacks to ensure that I/O operations do not block the
execution of other tasks.
---
---
### 71. **Why should you separate the Express app and server?**
Separating the app and server allows for more flexible configuration and easier testing of application logic
without starting an actual HTTP server.
---
---
### 73. **What is the framework that is used majorly in Node.js today?**
**Express.js** is the most commonly used framework for building web applications and APIs with Node.js.
---
### 74. **What are the security implementations that are present in Node.js?**
Security features include HTTPS support, built-in security headers (CORS), libraries like ‘helmet‘ for
HTTP header security, and JWT for authentication.
---
---
---
---
---
---
### 80. **What’s the difference between ’front-end’ and ’back-end’ development?**
Frontend development focuses on the user interface and user experience, while backend development
focuses on server-side logic, databases, and APIs.
---
---
---
---
---
---
### 86. **What is a thread pool, and which library handles it in Node.js?**
A thread pool is a collection of threads that can be reused for I/O operations. Node.js uses **libuv** to
manage its thread pool.
---
---
---
---
### 90. **What is meant by tracing in Node.js?**
Tracing refers to capturing detailed performance data for debugging and optimization, such as through
the ‘--trace‘ flag or using tracing tools.
---
---
### 92. **What is the difference between readFile and createReadStream in Node.js?**
- ‘readFile‘ reads the entire file into memory at once.
- ‘createReadStream‘ reads the file in chunks and is better for large files.
---
---
---
---
### 96. **How does the DNS lookup function work in Node.js?**
The ‘dns.lookup()‘ function performs DNS resolution, returning the IP address of a domain name.
‘‘‘javascript
const dns = require(’dns’);
dns.lookup(’example.com’, (err, address, family) => {
console.log(’Address: ’, address);
});
‘‘‘
---
---
### 98. **Does Node.js provide any Debugger?**
Yes, Node.js includes a built-in debugger that can be accessed via the ‘inspect‘ flag or by using
‘debugger‘ statements in your code.
---
### 99. **Do you have any past Node.js work experience?**
This is a personal question for interviewees.
---
### 100. **Do you have any experience working in the same industry as ours?**
This is a personal question for interviewees.
---
### 101. **Do you have any certification to boost your candidature for this Node.js role?**
This is a personal question for interviewees.
---
---
---
---
---
---
### 107. **Companies That Are Using Express JS**
- Uber
- Netflix
- IBM
- Accenture
---
---
---
---
---
---
---
---
---
logical..
---
‘‘‘javascript
let a = 5, b = 10;
let temp;
temp = a;
a = b;
b = temp;
console.log("After swapping:");
console.log("a =", a);
console.log("b =", b);
‘‘‘
---
‘‘‘javascript
let a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
console.log("After swapping:");
console.log("a =", a);
console.log("b =", b);
‘‘‘
---
### 3. **WAP to find Rupees and Paisa from a given amount (e.g. 12.50).**
‘‘‘javascript
let amount = 12.50;
let rupees = Math.floor(amount);
let paisa = Math.round((amount - rupees) * 100);
console.log(‘${rupees} Rupees‘);
console.log(‘${paisa} Paisa‘);
‘‘‘
---
### 4. **WAP to print the sum of digits of a given number (e.g., 768).**
‘‘‘javascript
let num = 768;
let sum = 0;
---
### 5. **WAP to print the sum of the first and last digit of a given number.**
‘‘‘javascript
function sumFirstAndLast(num) {
let firstDigit = num.toString()[0];
let lastDigit = num.toString()[num.toString().length - 1];
return parseInt(firstDigit) + parseInt(lastDigit);
}
console.log(sumFirstAndLast(768)); // Output: 15
console.log(sumFirstAndLast(8983)); // Output: 11
‘‘‘
---
### 6. **WAP to print the sum of the middle digits of a given number.**
‘‘‘javascript
function sumMiddleDigits(num) {
let str = num.toString();
if (str.length <= 2) return 0; // No middle digit for 1 or 2 digit numbers
let middle = str.slice(1, str.length - 1);
let sum = 0;
for (let i = 0; i < middle.length; i++) {
sum += parseInt(middle[i]);
}
return sum;
}
console.log(sumMiddleDigits(768)); // Output: 6
console.log(sumMiddleDigits(8983)); // Output: 17
‘‘‘
---
‘‘‘javascript
let num = 768;
let reverse = 0;
---
‘‘‘javascript
function isPalindrome(num) {
let original = num;
let reverse = 0;
---
‘‘‘javascript
function isArmstrong(num) {
let sum = 0;
let digits = num.toString().length;
let temp = num;
while (temp > 0) {
let digit = temp % 10;
sum += Math.pow(digit, digits);
temp = Math.floor(temp / 10);
}
---
‘‘‘javascript
function isMagicNumber(num) {
let sum = num;
---
‘‘‘javascript
function isPrime(num) {
if (num <= 1) return false;
return true;
}
---
---
‘‘‘javascript
function fibonacci(n) {
let a = 0, b = 1;
---
‘‘‘javascript
let num = 5;
for (let i = 1; i <= 10; i++) {
console.log(‘${num} * ${i} = ${num * i}‘);
}
‘‘‘
---
‘‘‘javascript
// Pattern 1:
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += j + " ";
}
console.log(row.trim());
}
‘‘‘
‘‘‘javascript
// Pattern 2:
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = i; j >= 1; j--) {
row += j + " ";
}
console.log(row.trim());
}
‘‘‘
‘‘‘javascript
// Pattern 3 (Reverse):
for (let i = 5; i >= 1; i--) {
let row = "";
for (let j = 5; j >= 6 - i; j--) {
row += j + " ";
}
console.log(row.trim());
}
‘‘‘
---
### 16. **WAP to find the sum and average of all array values.**
‘‘‘javascript
let arr = [10, 20, 30, 40];
let sum = arr.reduce((acc, num) => acc + num, 0);
let average = sum / arr.length;
console.log("Sum:", sum);
console.log("Average:", average);
‘‘‘
---
### 17. **WAP to find the maximum and minimum values in an array.**
‘‘‘javascript
let arr = [10, 20, 30, 5, 50];
let max = Math.max(...arr);
let min = Math.min(...arr);
console.log("Max:", max);
console.log("Min:", min);
‘‘‘
---
‘‘‘javascript
let arr = [1, 2, 3, 4, 5];
let reversed = arr.reverse();
console.log("Reversed array:", reversed);
‘‘‘
---
‘‘‘javascript
let arr = [1, 2, 3, 2, 1];
let isPalindrome = arr.join(’’) === arr.reverse().join(’’);
---
### 20. **WAP to sort an array in ascending and descending order using bubble sort.**
‘‘‘javascript
let arr = [5, 3, 8, 4, 2];
bubbleSort(arr, ’asc’);
console.log("Sorted in Ascending Order:", arr);
bubbleSort(arr, ’desc’);
console.log("Sorted in Descending Order:", arr);
‘‘‘
---
‘‘‘javascript
let arr = [1,
2, 3, 5];
let pos = 3;
let newElement = 4;
arr.splice(pos - 1, 0, newElement);
console.log("Array after insertion:", arr);
‘‘‘
---
### 22. **WAP to delete one element in an array using position or value.**
‘‘‘javascript
let arr = [1, 2, 3, 4, 5];
// Deleting by position
let pos = 2;
arr.splice(pos - 1, 1);
console.log("Array after deletion by position:", arr);
// Deleting by value
let value = 4;
arr = arr.filter(item => item !== value);
console.log("Array after deletion by value:", arr);
‘‘‘
---
‘‘‘javascript
let arr = [1, 2, 3, 3, 4, 5, 5];
let uniqueArr = [...new Set(arr)];
---
‘‘‘javascript
let arr = [1, 2, 3, 3, 4, 5, 5];
let uniqueArr = [...new Set(arr)];