0% found this document useful (0 votes)
3 views

answer

The document provides a comprehensive overview of JavaScript and Node.js concepts, including data types, hoisting, debugging, operators, scope, and functions. It also covers Node.js specifics such as its architecture, event-driven programming, and the use of Express.js. Additionally, it includes logical programming tasks and solutions related to JavaScript and Node.js.

Uploaded by

tanviladva01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

answer

The document provides a comprehensive overview of JavaScript and Node.js concepts, including data types, hoisting, debugging, operators, scope, and functions. It also covers Node.js specifics such as its architecture, event-driven programming, and the use of Express.js. Additionally, it includes logical programming tasks and solutions related to JavaScript and Node.js.

Uploaded by

tanviladva01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

JavaScript

1.What are the different data types present in javascript?


2.Explain Hoisting in javascript.
3.Why do we use the word “debugger” in javascript?
4.Difference between “ == “ and “ === “ operators.
5.Difference between var and let keyword in javascript.
6.Explain Implicit Type Coercion in javascript.
7.Is javascript a statically typed or a dynamically typed language?
8.What is NaN property in JavaScript?
9.Explain passed by value and passed by reference.
10.What is an Immediately Invoked Function in JavaScript?
11.What do you mean by strict mode in javascript and characteristics of javascript strict-mode?
12.Explain Higher Order Functions in javascript.
13.Explain “this” keyword.
14.What do you mean by Self Invoking Functions?
15.Explain call(), apply() and, bind() methods.
16.What is the difference between exec () and test () methods in javascript?
17.What is currying in JavaScript?
18.What are some advantages of using External JavaScript?
19.Explain Scope and Scope Chain in javascript.
20.Explain Closures in JavaScript.
21.Mention some advantages of javascript.
22.What are object prototypes?
23.What are callbacks?
24.What are the types of errors in javascript?
25.What is memoization?
26.What is recursion in a programming language?
27.What is the use of a constructor function in javascript?
28.What is DOM?
29.Which method is used to retrieve a character from a certain index?
30.What do you mean by BOM?
31.What is the distinction between client-side and server-side JavaScript?
32.What are arrow functions?
33.What do mean by prototype design pattern?
34.Differences between declaring variables using var, let and const.
35.What is the rest parameter and spread operator?
36.In JavaScript, how many different methods can you make an object?
37.What is the use of promises in javascript?
38.What are classes in javascript?
39.What are generator functions?
40.Explain WeakSet in javascript.
41.Why do we use callbacks?
42.Explain WeakMap in javascript.
43.What is Object Destructuring?
44.Difference between prototypal and classical inheritance
45.What is a Temporal Dead Zone?
46.What do you mean by JavaScript Design Patterns?
47.Is JavaScript a pass-by-reference or pass-by-value language?
48.Difference between Async/Await and Generators usage to achieve the same functionality.
49.What are the primitive data types in JavaScript?
50.What is the role of deferred scripts in JavaScript?
51.What has to be done in order to put Lexical Scoping into practice?
58. Write a function that performs binary search on a sorted array.
59. Implement a function that returns an updated array with r right rotations on an array of integers a .
60. Write the code for dynamically inserting new components.
61. Write the code given If two strings are anagrams of one another, then return true.
62. Write the code to find the vowels
63. In JavaScript, how do you turn an Object into an Array []?

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?

44. For Node.js, why does Google use the V8 engine?


45. Describe Node.js exit codes.
46. Explain the concept of middleware in Node.js.
47. What are the different types of HTTP requests?
48. How would you connect a MongoDB database to Node.js?
49. What is the purpose of NODE_ENV?
50. List the various Node.js timing features.
51. What is WASI, and why is it being introduced?
52. What is a first-class function in Javascript?
53. How do you manage packages in your Node.Js project?
54. How is Node.js better than other frameworks?
55. List down the two arguments that async. First, does the queue take as input?
56. What is the purpose of the module.exports?
57. What is the difference between JavaScript and Node.js?
58. What is the difference between asynchronous and synchronous functions?
59. What are the asynchronous tasks that should occur in an event loop?
60. What is the order of execution in control flow statements?
61. Are there any disadvantages to using Node.js?
62. What is the difference between Node.js and Ajax?
63. What is the advantage of using Node.js?
64. Does Node run on Windows?
65. Can you access DOM in Node?
66. Why is Node.JS quickly gaining attention from JAVA programmers?
67. What are the Challenges with Node.js?
68. What is "non-blocking" in node.js?
69. How does Node.js overcome the problem of blocking I/O operations?
70. How can we use async await in node.js?
71. Why should you separate the Express app and server?
72. Explain the concept of stub in Node.js.
73. What is the framework that is used majorly in Node.js today?
74. What are the security implementations that are present in Node.js?
75. What is Libuv?
76. What are global objects in Node.js?
77. Why is assert used in Node.js?
78. Why is ExpressJS used?
79. What is the use of the connect module in Node.js?
80. What’s the difference between ’front-end’ and ’back-end’ development?
81. What are LTS releases of Node.js?
82. What do you understand about ESLint?
83. How does Node.js handle the child threads?
84. What is an Event Emitter in Node.js?
85. How to Enhance Node.js Performance through Clustering?
86. What is a thread pool, and which library handles it in Node.js?
87. How to measure the duration of async operations?
88. How to measure the performance of async operations?
89. What are the types of streams available in Node.js?
90. What is meant by tracing in Node.js?
91. Where is package.json used in Node.js?
92. What is the difference between readFile and create Read Stream in Node.js?
93. What is the use of the crypto module in Node.js?
94. What is a passport in Node.js?
95. How to get information about a file in Node.js?
96. How does the DNS lookup function work in Node.js?

97. What is the difference between setImmediate() and setTimeout()?


98. Does Node.js provide any Debugger?
99. Do you have any past Node.js work experience?
100.
Do you have any experience working in the same industry as ours?
101.
Do you have any certification to boost your candidature for this Node.js role?
102.
What Is Express JS?
103.
Why Express JS?
104.
Features of Express JS
105.
Advantages of Using Express With Node.js
106.
Limitations of Express JS
107.
Companies That Are Using Express JS
108.
Installation and the First Program
109.
What is JSON Web Token?
110.
Advantages of Node.js authentication with JWT
111.
6. JSON Web Token Authentication with Node.js
112.
5. Node.js MySQL
113.
4. Node.js MongoDB
114.
What Is JSON Web Token?
115.
JSON Web Token Structure
116.
JWT Use Cases

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

6. WAP to print sum of middle of digits of given number?


Input:
768
Output:
6
Input :
8983
Output:
17
7. WAP to print reverse number of given number?
8. WAP to check given number is palindrome or not?
9. WAP to check given number is Armstrong number or not?
10. WAP to check given number is magic number or not?
11. WAP to check given number is prime number or not?
12. WAP to find a factorial of given number.
13. WAP to print below series Fibonacci series
0, 1, 1, 2, 3, 5, 8, 13, 21
14. Make table of given number:
No: 5
5*1=5 5*2=10 5*3=15 5*4=20
15. Pattern
1
12
123
1234
12345

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.

---

### 1. **What are the different data types present in JavaScript?**


JavaScript has 7 primitive data types:
- **Undefined**
- **Null**
- **Boolean**
- **Number**
- **BigInt**
- **String**
- **Symbol**

The non-primitive data type is:


- **Object** (includes arrays, functions, and other complex data structures).

---

### 2. **Explain Hoisting in JavaScript.**


Hoisting is a JavaScript behavior where variables and function declarations are moved to the top of their
containing scope during the compile phase. Only declarations are hoisted, not initializations.

Example:
‘‘‘javascript
console.log(a); // undefined
var a = 5;

console.log(b); // ReferenceError
let b = 10;
‘‘‘

---

### 3. **Why do we use the word “debugger” in JavaScript?**


The ‘debugger‘ statement in JavaScript pauses code execution and invokes the browser’s built-in
debugging tools. It’s useful for inspecting the state of variables and stepping through code to identify
issues.

Example:
‘‘‘javascript
function test() {
debugger; // Execution stops here
console.log("Hello World");
}
test();
‘‘‘

---

### 4. **Difference between ‘==‘ and ‘===‘ operators.**


- **‘==‘ (Loose equality)**: Compares values after type coercion.
- **‘===‘ (Strict equality)**: Compares both value and type without type coercion.

Example:
‘‘‘javascript
5 == ’5’; // true
5 === ’5’; // false
‘‘‘

---

### 5. **Difference between ‘var‘ and ‘let‘ keywords in JavaScript.**


- **‘var‘**: Function-scoped or globally scoped, can be re-declared within the same scope.
- **‘let‘**: Block-scoped, cannot be re-declared in the same scope.
Example:
‘‘‘javascript
var a = 10;
var a = 20; // Valid

let b = 10;
let b = 20; // SyntaxError
‘‘‘

---

### 6. **Explain Implicit Type Coercion in JavaScript.**


Implicit type coercion occurs when JavaScript automatically converts values from one type to another,
typically during operations like comparison or arithmetic.

Example:
‘‘‘javascript
’5’ + 2; // ’52’ (string)
’5’ - 2; // 3 (number)
‘‘‘

---

### 7. **Is JavaScript a statically typed or dynamically typed language?**


JavaScript is a **dynamically typed** language, meaning variable types are determined at runtime, and
the type can change during execution.

---

### 8. **What is NaN property in JavaScript?**


‘NaN‘ stands for "Not a Number." It is a special value representing an invalid number, such as when
dividing 0 by 0 or attempting to convert a non-numeric string to a number.

Example:
‘‘‘javascript
0 / 0; // NaN
"abc" * 2; // NaN
‘‘‘

---

### 9. **Explain passed by value and passed by reference.**


- **Pass by value**: For primitive types (e.g., numbers, strings, booleans), the function gets a copy of the
value.
- **Pass by reference**: For objects and arrays, the function gets a reference to the original object, so
changes to the object affect the original.

---

### 10. **What is an Immediately Invoked Function in JavaScript?**


An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it is defined.

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.

Enable it by adding ‘"use strict";‘ at the beginning.

---

### 12. **Explain Higher Order Functions in JavaScript.**


A higher-order function is a function that either takes one or more functions as arguments or returns a
function as a result.

Example:
‘‘‘javascript
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // map is a higher-order function
‘‘‘

---

### 13. **Explain “this” keyword.**


The ‘this‘ keyword refers to the context in which a function is called. It can refer to:
- The global object (‘window‘ in browsers) in non-strict mode.
- The object that calls the method.
- A specific object in constructors or classes.

---

### 14. **What do you mean by Self Invoking Functions?**


Self-invoking functions (also called IIFEs) are functions that invoke themselves immediately after being
defined.

Example:
‘‘‘javascript
(function() {
console.log("Self Invoking Function!");
})();
‘‘‘

---

### 15. **Explain ‘call()‘, ‘apply()‘, and ‘bind()‘ methods.**


- **‘call()‘**: Calls a function with a specific ‘this‘ context and individual arguments.
- **‘apply()‘**: Similar to ‘call()‘, but accepts arguments as an array.
- **‘bind()‘**: Returns a new function with a specified ‘this‘ context and predefined arguments.

Example:
‘‘‘javascript
function greet(name) {
console.log(‘Hello, ${name}‘);
}

greet.call(null, ’Alice’); // Hello, Alice


greet.apply(null, [’Bob’]); // Hello, Bob
const boundGreet = greet.bind(null, ’Charlie’);
boundGreet(); // Hello, Charlie
‘‘‘

---

### 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‘.

---

### 17. **What is currying in JavaScript?**


Currying is a technique where a function takes multiple arguments and transforms them into a series of
functions that each take one argument.

Example:
‘‘‘javascript
function add(a) {
return function(b) {
return a + b;
};
}
const add5 = add(5);
console.log(add5(3)); // 8
‘‘‘

---

### 18. **What are some advantages of using External JavaScript?**


- **Reusability**: The same JavaScript file can be reused across multiple HTML files.
- **Separation of concerns**: Keeps JavaScript separate from HTML, making the code cleaner.
- **Caching**: External scripts can be cached by the browser, improving page load time.

---

### 19. **Explain Scope and Scope Chain in JavaScript.**


- **Scope**: Refers to the area of code where a variable is accessible.
- **Scope Chain**: The sequence of environments that JavaScript searches through when trying to
resolve a variable, from the current scope to the global scope.

---

### 20. **Explain Closures in JavaScript.**


A closure is a function that retains access to its lexical scope, even when executed outside of that scope.

Example:
‘‘‘javascript
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}

const increment = outer();


increment(); // 1
increment(); // 2
‘‘‘

---

### 21. **Mention some advantages of JavaScript.**


- **Versatility**: JavaScript can be used for front-end, back-end, and mobile development.
- **Asynchronous programming**: Supports promises, ‘async/await‘, and callbacks.
- **Large ecosystem**: Rich libraries like React, Node.js, etc.
- **Event-driven programming**: Handles user interactions effectively.

---

### 22. **What are object prototypes?**


Every object in JavaScript has a prototype, which is another object from which it inherits properties and
methods. This forms the basis for inheritance in JavaScript.

---

### 23. **What are callbacks?**


A callback is a function passed into another function as an argument, which gets executed later, often
after an asynchronous operation.

---

### 24. **What are the types of errors in JavaScript?**


- **SyntaxError**: Occurs when there’s a mistake in the syntax.
- **ReferenceError**: Happens when a variable is referenced that does not exist.
- **TypeError**: Happens when a value is not of the expected type.
- **RangeError**: Happens when a number is outside of its valid range.

---

### 25. **What is memoization?**


Memoization is an optimization technique where results of expensive function calls are cached so that
subsequent calls with the same arguments can be retrieved from the cache instead of being recomputed.

---

### 26. **What is recursion in a programming language?**


Recursion is a process in which a function calls itself in order to solve a problem. The function should
have a base case to prevent infinite recursion.

---

### 27. **What is the use of a constructor function in JavaScript?**


A constructor function is used to create and initialize objects. It’s a blueprint for creating instances of
objects with the same properties and methods.

---

### 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’
‘‘‘

---

### 30. **What do you mean by BOM?**


The **Browser Object Model (BOM)** represents the browser window and provides methods to interact
with the browser’s environment, such as controlling the window size, interacting with the history, etc.

---

### 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).

---

### 32. **What are arrow functions?**


Arrow functions are a concise way to write functions in JavaScript. They have a shorter syntax and don’t
have their own ‘this‘, ‘arguments‘, or ‘super‘.

Example:
‘‘‘javascript
const sum = (a, b) => a + b;
‘‘‘

---

### 33. **What do you mean by prototype design pattern?**


The **Prototype Design Pattern** is used to create new objects by copying existing objects. It’s useful
when creating a new instance based on a prototype object.

---

### 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.

---

### 35. **What is the rest parameter and spread operator?**


- **Rest parameter (‘...args‘)**: Collects multiple arguments into a single array.
- **Spread operator (‘...‘)**: Expands an array or object into individual elements.

---

### 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)

---

### 37. **What is the use of promises in JavaScript?**


A **Promise** is used to handle asynchronous operations. It represents a value that might not be
available yet but will be resolved in the future.

---

### 38. **What are classes in JavaScript?**


Classes are a blueprint for creating objects with shared properties and methods. Introduced in ES6, they
are syntactical sugar over JavaScript’s prototype-based inheritance.

---

### 39. **What are generator functions?**


A **generator function** is a special type of function that can pause execution and return multiple values
over time using the ‘yield‘ keyword.

---

### 40. **Explain WeakSet in JavaScript.**


A **WeakSet** is a collection of objects, but unlike ‘Set‘, the objects in a ‘WeakSet‘ are held **weakly**,
meaning they can be garbage collected when there are no other references to them.

---

### 41. **Why do we use callbacks?**


Callbacks are used to handle asynchronous tasks (like reading files or making network requests) or to
ensure that code runs in a specific order.
---

### 42. **Explain WeakMap in JavaScript.**


A **WeakMap** is similar to a ‘Map‘, but it only holds **weak references** to its keys. If the key object is
garbage collected, the entry is removed from the map.

---

### 43. **What is Object Destructuring?**


**Object destructuring** is a shorthand way to extract properties from objects and assign them to
variables.

Example:
‘‘‘javascript
const person = { name: ’John’, age: 30 };
const { name, age } = person;
‘‘‘

---

### 44. **Difference between prototypal and classical inheritance**


- **Prototypal inheritance**: Objects inherit directly from other objects (used in JavaScript).
- **Classical inheritance**: Classes inherit from other classes, often seen in languages like Java or C++.

---

### 45. **What is a Temporal Dead Zone?**


The **Temporal Dead Zone (TDZ)** refers to the time between entering a scope and the variable being
initialized. During this time, accessing a ‘let‘ or ‘const‘ variable will result in a ReferenceError.

---

### 46. **What do you mean by JavaScript Design Patterns?**


**JavaScript Design Patterns** are common solutions to recurring problems in software development.
They provide reusable structures and guidelines for solving problems efficiently.

---

### 47. **Is JavaScript a pass-by-reference or pass-by-value language?**


JavaScript is **pass-by-value** for primitive types and **pass-by-reference** for objects and arrays.

---

### 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.

---

### 49. **What are the primitive data types in JavaScript?**


The 7 primitive data types are:
- Undefined
- Null
- Boolean
- Number
- String
- BigInt
- Symbol

---

### 50. **What is the role of deferred scripts in JavaScript?**


**Deferred scripts** are JavaScript files that will be executed after the HTML is parsed but before the
‘DOMContentLoaded‘ event is fired. They are useful for optimizing page load speed.

---

### 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;

while (left <= right) {


let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -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(’’);
}
‘‘‘

---

### 62. **Write the code to find the vowels.**


‘‘‘javascript
function findVowels(str) {
return str.match(/[aeiouAEIOU]/g) || [];
}
‘‘‘

---

### 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]
‘‘‘

---

Let me know if you’d like more details on any specific question!

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.

---

### 1. **What is Node.js? Where can you use it?**


Node.js is a runtime environment that allows you to run JavaScript on the server-side. It is commonly
used for building scalable web applications, APIs, and real-time applications such as chat applications
and live data streaming.

---

### 2. **Why use Node.js?**


Node.js is efficient for building scalable applications due to its event-driven, non-blocking I/O model. It is
well-suited for real-time applications, high-concurrency apps, and APIs that handle multiple requests
simultaneously.

---

### 3. **How does Node.js work?**


Node.js runs JavaScript code outside the browser using the V8 engine. It operates on a single thread with
an event loop that handles asynchronous requests, which makes it non-blocking.

---

### 4. **Why is Node.js Single-threaded?**


Node.js is single-threaded because it relies on asynchronous I/O operations. This allows it to handle
multiple requests without being blocked by I/O tasks, making it more efficient for I/O-heavy applications.

---

### 5. **If Node.js is single-threaded, then how does it handle concurrency?**


Node.js handles concurrency through the event loop. It processes asynchronous operations like I/O tasks
in the background, allowing the main thread to continue executing while the tasks are handled by
separate threads via libuv.

---

### 6. **Explain callback in Node.js.**


A callback is a function passed as an argument to another function. It gets executed after the completion
of the asynchronous operation, allowing for non-blocking execution.

---

### 7. **What are the advantages of using promises instead of callbacks?**


Promises provide a cleaner and more readable way to handle asynchronous operations compared to
callbacks. They help avoid "callback hell" by allowing chaining and better error handling.

---

### 8. **How would you define the term I/O?**


I/O (Input/Output) refers to operations that involve reading or writing data, such as reading files,
accessing databases, or sending/receiving data over the network.

---

### 9. **How is Node.js most frequently used?**


Node.js is frequently used for building APIs, web servers, real-time applications (like chat apps),
streaming services, and server-side tools.

---
### 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.

---

### 11. **What is NPM?**


NPM (Node Package Manager) is a package manager for JavaScript that allows developers to install,
update, and manage dependencies in a Node.js project.

---

### 12. **What are the modules in Node.js?**


Modules in Node.js are reusable blocks of code that can be imported and used in other parts of an
application. Node.js comes with built-in modules like ‘fs‘ (file system), ‘http‘, and ‘path‘.

---

### 13. **What is the purpose of the module.exports?**


‘module.exports‘ is used to export functionality (functions, objects, variables) from one module so it can
be required and used in other modules.

---

### 14. **What is the difference between Angular and Node.js?**


Angular is a frontend JavaScript framework used for building web applications, while Node.js is a backend
runtime environment used for running JavaScript server-side.

---

### 15. **Which database is more popularly used with Node.js?**


MongoDB is commonly used with Node.js due to its non-relational nature, flexibility, and ease of
integration with JavaScript applications.

---

### 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)

---

### 17. **What are the pros and cons of Node.js?**


**Pros**:
- Fast execution with non-blocking I/O
- Single-threaded with an event-driven model
- Large ecosystem via npm

**Cons**:
- Not suitable for CPU-heavy tasks
- Callback hell in complex asynchronous code
- Limited support for multi-threading

---

### 18. **What is the command used to import external libraries?**


‘‘‘javascript
const library = require(’library-name’);
‘‘‘

---

### 19. **What does event-driven programming mean?**


Event-driven programming involves writing code that responds to events (like user inputs or messages
from other systems) rather than a predefined sequence of commands.

---

### 20. **What is an Event Loop in Node.js?**


The event loop in Node.js is responsible for executing asynchronous callbacks. It handles tasks like I/O
operations and timers in a non-blocking manner.

---

### 21. **What is an EventEmitter in Node.js?**


EventEmitter is a class in Node.js that allows objects to emit events and register listeners for those
events.

---

### 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()‘).

---

### 23. **What is the package.json file?**


‘package.json‘ is a configuration file in Node.js projects that contains metadata about the project (e.g.,
name, version) and lists dependencies and scripts.

---

### 24. **How would you use a URL module in Node.js?**


The ‘url‘ module helps in parsing, formatting, and manipulating URLs. Example:
‘‘‘javascript
const url = require(’url’);
const myUrl = new URL(’https://example.com/path?name=Node’);
console.log(myUrl.hostname); // Outputs: example.com
‘‘‘

---

### 25. **What is the Express.js package?**


Express.js is a minimal and flexible web framework for Node.js, providing a robust set of features for web
and mobile applications.
---

### 26. **How do you create a simple Express.js application?**


‘‘‘javascript
const express = require(’express’);
const app = express();
app.get(’/’, (req, res) => res.send(’Hello World’));
app.listen(3000, () => console.log(’App running on port 3000’));
‘‘‘

---

### 27. **What are streams in Node.js?**


Streams are objects that allow reading or writing data sequentially. Types of streams include readable,
writable, and duplex streams.

---

### 28. **How do you install, update, and delete a dependency?**


- Install: ‘npm install <package-name>‘
- Update: ‘npm update <package-name>‘
- Delete: ‘npm uninstall <package-name>‘

---

### 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’));
‘‘‘

---

### 30. **Explain asynchronous and non-blocking APIs in Node.js.**


Asynchronous APIs in Node.js do not block the execution thread while waiting for operations (e.g., file
I/O). Non-blocking means the thread continues to execute other tasks while waiting for the asynchronous
task to finish.

---

### 31. **How do we implement async in Node.js?**


Using ‘async/await‘ syntax, you can handle asynchronous operations in a more readable and
synchronous-like manner:
‘‘‘javascript
async function fetchData() {
const data = await someAsyncFunction();
console.log(data);
}
‘‘‘
---

### 32. **What is a callback function in Node.js?**


A callback function is a function passed as an argument to another function, which is executed after the
completion of the asynchronous operation.

---

### 33. **What is REPL in Node.js?**


REPL stands for Read-Eval-Print-Loop. It is an interactive shell where you can execute JavaScript
commands and see results immediately.

---

### 34. **What is the control flow function?**


Control flow functions in Node.js are used to manage the flow of asynchronous code (e.g., ‘setTimeout()‘,
‘setImmediate()‘, ‘process.nextTick()‘).

---

### 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.

---

### 37. **What is the buffer class in Node.js?**


The Buffer class provides a way to work with binary data directly in Node.js, which is useful for dealing
with streams, file I/O, or network protocols.

---

### 38. **What is piping in Node.js?**


Piping allows you to take the output of one stream and send it directly as input to another stream (e.g.,
reading a file and writing it to another file).

---

### 39. **What are

some of the flags used in the read/write operations in files?**


Flags for file operations include:
- ‘’r’‘: Open a file for reading.
- ‘’w’‘: Open a file for writing.
- ‘’a’‘: Open a file for appending.

---
### 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);
});
‘‘‘

---

### 41. **What is callback hell?**


Callback hell refers to the difficulty in reading and maintaining code with nested callbacks, often leading to
deeply indented code structures.

---

### 42. **What is a reactor pattern in Node.js?**


The reactor pattern in Node.js refers to the event-driven model where the event loop handles events and
delegates them to appropriate callbacks or handlers.

---

### 43. **What is a test pyramid in Node.js?**


A test pyramid is a concept for structuring tests in software development, where most tests are unit tests,
fewer are integration tests, and even fewer are end-to-end tests.

---

### 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.

---

### 45. **Describe Node.js exit codes.**


Exit codes indicate the status of a Node.js application when it terminates. A ‘0‘ exit code typically means
success, while any non-zero code indicates an error.

---

### 46. **Explain the concept of middleware in Node.js.**


Middleware are functions that have access to the request, response, and the next function in the
application’s request-response cycle. Middleware is used for tasks like authentication, logging, or error
handling.

---

### 47. **What are the different types of HTTP requests?**


- **GET**: Retrieve data
- **POST**: Submit data
- **PUT**: Update data
- **DELETE**: Remove data
---

### 48. **How would you connect a MongoDB database to Node.js?**


‘‘‘javascript
const mongoose = require(’mongoose’);
mongoose.connect(’mongodb://localhost:27017/mydatabase’, { useNewUrlParser: true,
useUnifiedTopology: true });
‘‘‘

---

### 49. **What is the purpose of NODE_ENV?**


‘NODE_ENV‘ is an environment variable that specifies the environment in which a Node.js application is
running (e.g., development, production, or testing).

---

### 50. **List the various Node.js timing features.**


- ‘setTimeout()‘: Executes a function after a specified delay.
- ‘setInterval()‘: Repeats a function at specified intervals.
- ‘setImmediate()‘: Executes a function after the current event loop cycle.

---

### 51. **What is WASI, and why is it being introduced?**


WASI (WebAssembly System Interface) is a set of system-level APIs for running WebAssembly (Wasm)
outside of browsers. It allows Wasm modules to interact with the operating system securely.

---

### 52. **What is a first-class function in JavaScript?**


A first-class function means functions are treated as values in JavaScript. They can be assigned to
variables, passed as arguments, and returned from other functions.

---

### 53. **How do you manage packages in your Node.js project?**


Use npm to install, update, and manage dependencies. The dependencies are listed in the ‘package.json‘
file.

---

### 54. **How is Node.js better than other frameworks?**


Node.js excels in handling I/O-heavy applications due to its non-blocking, event-driven nature. It’s
scalable and efficient for real-time applications.

---

### 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()‘.

---

### 57. **What is the difference between JavaScript and Node.js?**


JavaScript is a programming language, while Node.js is a runtime environment that allows you to run
JavaScript on the server side.

---

### 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.

---

### 60. **What is the order of execution in control flow statements?**


Control flow statements (like ‘if‘, ‘else‘, ‘for‘, ‘while‘) are executed sequentially, with conditional branches
determining the path taken.

---

### 61. **Are there any disadvantages to using Node.js?**


Disadvantages include:
- Not ideal for CPU-heavy operations.
- Callback hell in asynchronous code.
- Limited multi-threading support.

---

### 62. **What is the difference between Node.js and Ajax?**


Node.js is a server-side runtime environment, while Ajax (Asynchronous JavaScript and XML) is a
technique for making asynchronous requests from a client (browser) to a server.

---

### 63. **What is the advantage of using Node.js?**


Node.js provides high performance for I/O-bound applications, scalability, and allows JavaScript to be
used for both frontend and backend development.

---

### 64. **Does Node run on Windows?**


Yes, Node.js is cross-platform and runs on Windows, macOS, and Linux.

---
### 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.

---

### 67. **What are the Challenges with Node.js?**


Challenges include:
- Managing CPU-bound tasks.
- Debugging asynchronous code.
- Handling scaling in large applications.

---

### 68. **What is "non-blocking" in Node.js?**


Non-blocking means that I/O operations do not block the execution of other code. Node.js continues to
process other tasks while waiting for I/O operations to complete.

---

### 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.

---

### 70. **How can we use async/await in Node.js?**


‘async/await‘ is used to handle asynchronous code in a synchronous manner, improving readability:
‘‘‘javascript
async function fetchData() {
const data = await someAsyncFunction();
console.log(data);
}
‘‘‘

---

### 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.

---

### 72. **Explain the concept of stub in Node.js.**


A stub is a placeholder or mock function used to simulate the behavior of real functions during testing.

---

### 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.

---

### 75. **What is Libuv?**


Libuv is a cross-platform library used by Node.js to handle asynchronous I/O operations. It provides the
event loop and manages tasks like networking, file system access, and DNS queries.

---

### 76. **What are global objects in Node.js?**


Global objects include:
- ‘__dirname‘: Current directory name.
- ‘__filename‘: Current file name.
- ‘process‘: Provides information about the current process.
- ‘global‘: The global namespace object.

---

### 77. **Why is assert used in Node.js?**


‘assert‘ is used in testing to check conditions and throw errors when expectations are not met.

---

### 78. **Why is ExpressJS used?**


Express.js is used to simplify the process of building web applications and APIs in Node.js by providing
useful utilities and middleware for routing, request handling, and more.

---

### 79. **What is the use of the connect module in Node.js?**


‘connect‘ is a middleware framework for Node.js, often used with Express to manage HTTP
request/response cycles and session handling.

---

### 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.

---

### 81. **What are LTS releases of Node.js?**


LTS (Long Term Support) releases are stable versions of Node.js that are supported for a longer period
(usually 18 months) and receive critical bug fixes and security patches.

---

### 82. **What do you understand about ESLint?


**
ESLint is a static code analysis tool used to identify problematic patterns in JavaScript code and enforce
coding standards.

---

### 83. **How does Node.js handle child threads?**


Node.js handles child threads using worker threads or child processes for parallel execution, offloading
CPU-heavy tasks.

---

### 84. **What is an Event Emitter in Node.js?**


An ‘EventEmitter‘ is a class that allows objects to emit events and register listeners to handle those
events.

---

### 85. **How to Enhance Node.js Performance through Clustering?**


Clustering in Node.js allows you to utilize multiple CPU cores by creating child processes that share the
same server port.

---

### 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.

---

### 87. **How to measure the duration of async operations?**


You can use ‘console.time()‘ and ‘console.timeEnd()‘ to measure the duration of async operations.
‘‘‘javascript
console.time(’asyncOperation’);
someAsyncFunction().then(() => {
console.timeEnd(’asyncOperation’);
});
‘‘‘

---

### 88. **How to measure the performance of async operations?**


Use built-in Node.js tools like the ‘perf_hooks‘ module to measure performance.

---

### 89. **What are the types of streams available in Node.js?**


Types of streams include:
- **Readable streams** (e.g., ‘fs.createReadStream‘)
- **Writable streams** (e.g., ‘fs.createWriteStream‘)
- **Duplex streams** (e.g., network sockets)
- **Transform streams** (e.g., gzip compression)

---
### 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.

---

### 91. **Where is package.json used in Node.js?**


‘package.json‘ is used to define project metadata, dependencies, and scripts for Node.js projects.

---

### 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.

---

### 93. **What is the use of the crypto module in Node.js?**


The ‘crypto‘ module provides cryptographic functionality, including hashing, encryption, and decryption.

---

### 94. **What is a passport in Node.js?**


Passport.js is an authentication middleware for Node.js, supporting various strategies like OAuth, JWT,
and local authentication.

---

### 95. **How to get information about a file in Node.js?**


Use ‘fs.stat()‘ to retrieve information like file size, modification time, and permissions.
‘‘‘javascript
fs.stat(’file.txt’, (err, stats) => {
console.log(stats);
});
‘‘‘

---

### 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);
});
‘‘‘

---

### 97. **What is the difference between setImmediate() and setTimeout()?**


- ‘setImmediate()‘ executes the callback after the current event loop cycle.
- ‘setTimeout()‘ executes the callback after the specified delay in milliseconds.

---
### 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.

---

### 102. **What Is Express JS?**


Express.js is a fast, unopinionated web framework for Node.js, designed for building web applications and
APIs.

---

### 103. **Why Express JS?**


Express.js simplifies routing, middleware handling, and HTTP request/response management, making it
easier to develop web applications.

---

### 104. **Features of Express JS**


- Middleware support
- Routing system
- Template engine support
- Error handling
- API creation support

---

### 105. **Advantages of Using Express With Node.js**


Express simplifies application routing, middleware integration, and error handling, making it easier to build
robust APIs and web applications.

---

### 106. **Limitations of Express JS**


Express lacks built-in solutions for some advanced features like authentication, which requires third-party
libraries for full functionality.

---
### 107. **Companies That Are Using Express JS**
- Uber
- Netflix
- IBM
- Accenture

---

### 108. **Installation and the First Program**


‘‘‘bash
npm install express
‘‘‘
‘‘‘javascript
const express = require(’express’);
const app = express();
app.get(’/’, (req, res) => res.send(’Hello Express’));
app.listen(3000, () => console.log(’App running on port 3000’));
‘‘‘

---

### 109. **What is JSON Web Token?**


JWT is a compact, URL-safe means of representing claims between two parties, typically used for user
authentication.

---

### 110. **Advantages of Node.js authentication with JWT**


- Stateless authentication
- Secure and compact token structure
- Easy to integrate with APIs

---

### 111. **JSON Web Token Authentication with Node.js**


To authenticate with JWT in Node.js, generate a token using a secret key and send it as part of the HTTP
request header.

---

### 112. **Node.js MySQL**


You can use the ‘mysql‘ module in Node.js to interact with MySQL databases by performing operations
like querying, inserting, and updating data.

---

### 113. **Node.js MongoDB**


You can use ‘mongoose‘ to interact with MongoDB in Node.js, allowing for easier schema-based querying
and object mapping.

---

### 114. **What Is JSON Web Token?**


JWT is used to securely transmit information between parties. It is often used for authentication in APIs.
---

### 115. **JSON Web Token Structure**


JWT consists of three parts:
1. Header
2. Payload
3. Signature

---

### 116. **JWT Use Cases**


- API authentication
- Single sign-on (SSO)
- Secure data transmission

---

logical..

---

### 1. **WAP to Swap two variables using a third variable.**

‘‘‘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);
‘‘‘

---

### 2. **WAP to Swap two variables without using a third variable.**

‘‘‘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;

while (num > 0) {


sum += num % 10;
num = Math.floor(num / 10);
}

console.log("Sum of digits:", sum);


‘‘‘

---

### 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
‘‘‘

---

### 7. **WAP to print the reverse of a given number.**

‘‘‘javascript
let num = 768;
let reverse = 0;

while (num > 0) {


reverse = reverse * 10 + (num % 10);
num = Math.floor(num / 10);
}

console.log("Reversed number:", reverse);


‘‘‘

---

### 8. **WAP to check if a number is palindrome or not.**

‘‘‘javascript
function isPalindrome(num) {
let original = num;
let reverse = 0;

while (num > 0) {


reverse = reverse * 10 + (num % 10);
num = Math.floor(num / 10);
}

return original === reverse;


}

console.log(isPalindrome(121)); // Output: true


console.log(isPalindrome(123)); // Output: false
‘‘‘

---

### 9. **WAP to check if a number is an Armstrong number or not.**

‘‘‘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);
}

return sum === num;


}

console.log(isArmstrong(153)); // Output: true


console.log(isArmstrong(123)); // Output: false
‘‘‘

---

### 10. **WAP to check if a number is a magic number or not.**

‘‘‘javascript
function isMagicNumber(num) {
let sum = num;

while (sum > 9) {


sum = sum.toString().split(’’).reduce((acc, digit) => acc + parseInt(digit), 0);
}

return sum === 1;


}

console.log(isMagicNumber(19)); // Output: true


console.log(isMagicNumber(23)); // Output: false
‘‘‘

---

### 11. **WAP to check if a number is a prime number or not.**

‘‘‘javascript
function isPrime(num) {
if (num <= 1) return false;

for (let i = 2; i <= Math.sqrt(num); i++) {


if (num % i === 0) return false;
}

return true;
}

console.log(isPrime(7)); // Output: true


console.log(isPrime(10)); // Output: false
‘‘‘

---

### 12. **WAP to find the factorial of a given number.**


‘‘‘javascript
function factorial(num) {
if (num === 0 || num === 1) return 1;
return num * factorial(num - 1);
}

console.log(factorial(5)); // Output: 120


‘‘‘

---

### 13. **WAP to print Fibonacci series.**

‘‘‘javascript
function fibonacci(n) {
let a = 0, b = 1;

while (n-- > 0) {


console.log(a);
let temp = a;
a = b;
b = temp + b;
}
}

fibonacci(9); // Output: 0, 1, 1, 2, 3, 5, 8, 13, 21


‘‘‘

---

### 14. **WAP to make a multiplication table of a given number.**

‘‘‘javascript
let num = 5;
for (let i = 1; i <= 10; i++) {
console.log(‘${num} * ${i} = ${num * i}‘);
}
‘‘‘

---

### 15. **Pattern Printing Programs**

‘‘‘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);
‘‘‘

---

### 18. **WAP to reverse an array.**

‘‘‘javascript
let arr = [1, 2, 3, 4, 5];
let reversed = arr.reverse();
console.log("Reversed array:", reversed);
‘‘‘

---

### 19. **WAP to check if an array is a palindrome or not.**

‘‘‘javascript
let arr = [1, 2, 3, 2, 1];
let isPalindrome = arr.join(’’) === arr.reverse().join(’’);

console.log("Is palindrome:", isPalindrome);


‘‘‘

---

### 20. **WAP to sort an array in ascending and descending order using bubble sort.**

‘‘‘javascript
let arr = [5, 3, 8, 4, 2];

function bubbleSort(arr, order = ’asc’) {


for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (order === ’asc’ ? arr[j] > arr[j + 1] : arr[j] < arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
}

bubbleSort(arr, ’asc’);
console.log("Sorted in Ascending Order:", arr);

bubbleSort(arr, ’desc’);
console.log("Sorted in Descending Order:", arr);
‘‘‘

---

### 21. **WAP to insert one element at a particular position in an array.**

‘‘‘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);
‘‘‘

---

### 23. **WAP to delete duplicate values in an array.**

‘‘‘javascript
let arr = [1, 2, 3, 3, 4, 5, 5];
let uniqueArr = [...new Set(arr)];

console.log("Array with unique values:", uniqueArr);


‘‘‘

---

### 24. **WAP to find unique values in an array.**

‘‘‘javascript
let arr = [1, 2, 3, 3, 4, 5, 5];
let uniqueArr = [...new Set(arr)];

console.log("Unique values:", uniqueArr);


‘‘‘

You might also like