node js interview questuion with DSA coding question 2026
node js interview questuion with DSA coding question 2026

80+ Questions | Arrays, Objects, DSA, System Design

Created By: Dheeraj Singh



1. JavaScript Fundamentals

1. What are the differences between `var`, `let`, and `const`?
`var` is function-scoped and hoisted with `undefined`. `let` and `const` are block-scoped and hoisted but reside in the “Temporal Dead Zone” (TDZ) until declared. `const` requires initialization and cannot be reassigned (though objects/arrays are mutable).
2. Explain Closures with a practical use case.
A closure is a function having access to its parent scope even after the parent function has closed. Use case: Data encapsulation (private variables), creating API wrappers, or memoization.
3. What is the Event Loop?
Mechanism handling async callbacks. Checks if Call Stack is empty. If yes, pushes tasks from Microtask Queue (Promises) first, then Macrotask Queue (setTimeout) onto the stack.
4. `==` vs `===`?
`==` allows type coercion (`5 == ‘5’` is true). `===` is strict equality (`5 === ‘5’` is false). Always use `===`.
5. Explain `this` context.
Refers to the object executing the function. **Global:** window/global. **Method:** object itself. **Constructor:** new instance. **Arrow Func:** inherits from outer scope.
6. Call vs Apply vs Bind?
`call(obj, arg1)`: Invokes immediately. `apply(obj, [args])`: Invokes immediately with array. `bind(obj)`: Returns new function with context bound.
7. What is the Temporal Dead Zone (TDZ)?
Time between scope start and variable declaration (`let`/`const`) where accessing the variable throws `ReferenceError`.
8. `null` vs `undefined`?
`undefined`: Variable declared but not assigned. `null`: Explicit assignment of “no value”. `typeof null` is ‘object’ (legacy bug).
9. What is Event Bubbling/Capturing?
**Capturing:** Root -> Target. **Bubbling:** Target -> Root. Events bubble by default. `e.stopPropagation()` stops it.
10. Explain Prototypal Inheritance.
Objects access properties via a prototype chain. If a prop isn’t on the object, JS checks `__proto__` recursively until `null`.
11. What is a Higher-Order Function?
A function taking another function as an arg (callback) or returning a function. E.g., `map`, `filter`.
12. Deep Copy vs Shallow Copy?
**Shallow:** Copies references (nested objects shared). `Object.assign`. **Deep:** Copies values recursively. `JSON.parse(JSON.stringify)` or `structuredClone()`.
13. What is a Promise?
Object representing async completion. States: Pending, Fulfilled, Rejected. Solves callback hell.
14. Async/Await vs `.then()`?
Async/Await is syntactic sugar making async code look synchronous. Easier `try/catch` error handling.
15. What are Generator Functions (`function*`)?
Functions that can be paused (`yield`) and resumed (`next`). Good for infinite streams or iterators.

2. Array & Object Methods (Mastery)

16. Difference between `map`, `forEach`, `filter`, `reduce`?
  • `map`: Returns new array with transformed elements.
  • `forEach`: Iterates only, returns `undefined`.
  • `filter`: Returns new array with elements passing a condition.
  • `reduce`: Accumulates array to a single value.
17. `slice` vs `splice`?
`slice(start, end)`: Returns a new array (immutable).
`splice(start, deleteCount, …items)`: Modifies the original array (mutable).
18. How to remove duplicates from an Array?
const arr = [1, 2, 2, 3];
const unique = [...new Set(arr)];

19. `Object.keys` vs `Object.values` vs `Object.entries`?
`keys`: Array of keys.
`values`: Array of values.
`entries`: Array of `[key, value]` pairs.
20. `Object.freeze()` vs `Object.seal()`?
`freeze()`: Completely immutable (no add, remove, or modify props).
`seal()`: Cannot add/remove props, but can modify existing values.
21. Flatten an array without `.flat()`?
function flatten(arr) {
  return arr.reduce((acc, val) => 
    Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []
  );
}

22. How to check if a key exists in an Object?
1. `’key’ in obj`
2. `obj.hasOwnProperty(‘key’)`
3. `obj.key !== undefined` (unreliable if value IS undefined)
23. Explain `Array.from()`.
Creates a new array from an array-like or iterable object. E.g., `Array.from(‘foo’)` -> `[‘f’,’o’,’o’]`.
24. Find intersection of two arrays.
const intersection = arr1.filter(x => arr2.includes(x));
// Optimized: use Set for O(1) lookup
const set2 = new Set(arr2);
const intersection = arr1.filter(x => set2.has(x));

25. Sort an array of objects by a property.
users.sort((a, b) => a.age - b.age); // Ascending
users.sort((a, b) => b.age - a.age); // Descending

3. Node.js Internals

26. Why is Node.js single-threaded but non-blocking?
It uses libuv to delegate I/O tasks (file, network) to the OS. The main thread simply registers callbacks and continues.
27. `process.nextTick` vs `setImmediate`?
`nextTick`: Fires immediately after current code, **before** the event loop continues (Microtask). `setImmediate`: Fires in the Check phase, **after** I/O callbacks.
28. Explain Streams and their types.
Efficient data handling (chunk by chunk). 1. Readable 2. Writable 3. Duplex (Both) 4. Transform (Modify data while writing, e.g., Compression).
29. What is the `cluster` module?
Allows creating child processes (workers) that share the server port to utilize multi-core systems.
30. What are `worker_threads`?
For CPU-intensive JS operations. Unlike Cluster (processes), Workers are threads sharing memory within one process.
31. `spawn` vs `fork` vs `exec`?
`exec`: Buffers output (small tasks). `spawn`: Streams output (large tasks). `fork`: Node-specific spawn with IPC channel.
32. What is a Buffer?
Raw binary data storage. Fixed memory allocation outside V8 heap.
33. Handling uncaught exceptions?
`process.on(‘uncaughtException’)`. Best practice: Log error, clean up, and restart process (state is corrupted).
34. What is `package-lock.json`?
Ensures exact dependency versions and integrity hashes are consistent across all installations.
35. CommonJS vs ES Modules?
CommonJS: `require/module.exports` (Dynamic, Sync). ESM: `import/export` (Static, Async).

4. Express.js & API Design

36. What is Middleware?
Function with access to `req`, `res`, and `next`. Can modify request, end response, or pass control.
37. `req.params` vs `req.query` vs `req.body`?
`params`: URL segments (`/user/:id`). `query`: Query string (`?sort=asc`). `body`: POST data (JSON).
38. Error Handling in Express?
Middleware with 4 arguments: `(err, req, res, next)`. Place at end of stack.
39. PUT vs PATCH?
PUT: Replace entire resource. PATCH: Partial update.
40. HTTP Status Codes (201, 401, 403, 500)?
201 Created, 401 Unauthorized (Auth missing), 403 Forbidden (Auth present, permission missing), 500 Server Error.
41. What is CORS?
Cross-Origin Resource Sharing. Security headers allowing browser to make requests to a different domain.
42. Difference between Controller and Service layer?
**Controller:** Handles HTTP (req/res, validation). **Service:** Contains Business Logic (DB calls, calculations).
43. How to prevent Request Flooding?
Rate Limiting (`express-rate-limit`, Redis).

5. Databases (SQL & NoSQL)

44. SQL vs NoSQL?
SQL: Structured, Relational, ACID, Scaling Vertical. NoSQL: Unstructured, Flexible, CAP, Scaling Horizontal.
45. What is ACID?
Atomicity, Consistency, Isolation, Durability. Ensures reliable transactions.
46. Indexing Pros/Cons?
Pros: Faster Reads. Cons: Slower Writes, Storage overhead.
47. N+1 Problem?
Fetching Parent (1 query), then iterating to fetch Children (N queries). Fix: JOINs or `$lookup`.
48. Redis Use Cases?
Caching, Session Store, Rate Limiting, Pub/Sub, Leaderboards.
49. MongoDB Aggregation Pipeline?
Framework for data processing. Steps: `$match`, `$lookup`, `$group`, `$project`, `$sort`.
50. Normalization vs Denormalization?
Normalization: Reduce redundancy (SQL). Denormalization: Duplicate data for faster reads (NoSQL).

6. System Design

51. Horizontal vs Vertical Scaling?
Horizontal: Add more machines (Load Balancer). Vertical: Add more power (CPU/RAM) to one machine.
52. How does a Load Balancer work?
Distributes traffic across servers using algorithms (Round Robin, Least Connections).
53. Message Queues (RabbitMQ/Kafka)?
Decouple services. Async processing. Handle traffic spikes.
54. Design a URL Shortener.
API: POST/GET. DB: Key-Value store. Algo: Base62 encoding of ID. Caching: Redis for hot links.
55. Caching Strategies?
Cache-Aside (Lazy), Write-Through, Write-Back.

7. DSA: Basic Challenges (Coding)

56. Reverse a String.
function reverseString(str) {
  return str.split('').reverse().join('');
  // Manual: Loop backwards
}

57. Check for Palindrome.
function isPalindrome(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return clean === clean.split('').reverse().join('');
}

58. Find Factorial (Recursive).
function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}

59. Find Max number in Array.
const max = Math.max(...arr);
// Or reduce: arr.reduce((a, b) => a > b ? a : b);

60. Fibonacci Sequence.
function fibonacci(n) {
  const seq = [0, 1];
  for (let i = 2; i < n; i++) {
    seq[i] = seq[i-1] + seq[i-2];
  }
  return seq;
}

8. DSA: Intermediate Challenges

61. Two Sum (Hash Map Approach).
function twoSum(nums, target) {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    const diff = target - nums[i];
    if (map.has(diff)) return [map.get(diff), i];
    map.set(nums[i], i);
  }
}

62. Valid Anagram.
function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  const map = {};
  for (let c of s) map[c] = (map[c] || 0) + 1;
  for (let c of t) {
    if (!map[c]) return false;
    map[c]--;
  }
  return true;
}

63. Remove Nth Node from End of List.
Use two pointers. Move `fast` pointer `n` steps ahead. Then move both `slow` and `fast` until `fast` reaches the end. `slow` is now at node before target.
64. Group Anagrams.
function groupAnagrams(strs) {
  const map = {};
  for (let s of strs) {
    const key = s.split('').sort().join('');
    if (!map[key]) map[key] = [];
    map[key].push(s);
  }
  return Object.values(map);
}

65. Maximum Subarray (Kadane’s Algorithm).
function maxSubArray(nums) {
  let currentMax = nums[0];
  let globalMax = nums[0];
  for (let i = 1; i < nums.length; i++) {
    currentMax = Math.max(nums[i], currentMax + nums[i]);
    globalMax = Math.max(globalMax, currentMax);
  }
  return globalMax;
}

9. DSA: Advanced Challenges

66. Reverse a Linked List.
function reverseList(head) {
  let prev = null;
  let curr = head;
  while(curr) {
    let next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}

67. Binary Tree Level Order Traversal (BFS).
function levelOrder(root) {
  if (!root) return [];
  const queue = [root];
  const result = [];
  while (queue.length) {
    const levelSize = queue.length;
    const currentLevel = [];
    for (let i=0; i < levelSize; i++) {
      const node = queue.shift();
      currentLevel.push(node.val);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
    result.push(currentLevel);
  }
  return result;
}

68. Validate Binary Search Tree (BST).
Use DFS (Recursive). Pass `min` and `max` limits.

function isValidBST(root, min = -Infinity, max = Infinity) {
  if (!root) return true;
  if (root.val <= min || root.val >= max) return false;
  return isValidBST(root.left, min, root.val) && 
         isValidBST(root.right, root.val, max);
}

69. Merge Intervals.
Sort by start time. Iterate and merge if current start < prev end.
intervals.sort((a, b) => a[0] - b[0]);
const res = [intervals[0]];
for (let curr of intervals) {
  let prev = res[res.length - 1];
  if (curr[0] <= prev[1]) {
    prev[1] = Math.max(prev[1], curr[1]);
  } else {
    res.push(curr);
  }
}

70. Detect Cycle in a Linked List.
Floyd's Tortoise and Hare algorithm. Use two pointers (slow/fast). If they meet, there is a cycle.

10. Rapid Fire (Security, Testing, Misc)

71. What is XSS?
Injecting malicious scripts into web pages. Prevent by sanitizing input.
72. What is CSRF?
Forcing users to execute unwanted actions. Prevent with CSRF Tokens/SameSite cookies.
73. Symmetric vs Asymmetric Encryption?
Symmetric: 1 key (Speed). Asymmetric: Public/Private keys (Security).
74. Unit vs Integration Testing?
Unit: Isolated components. Integration: Interaction between modules/DB.
75. What is Docker?
Containerization platform packaging app+libs to run anywhere reliably.
76. What is CI/CD?
Continuous Integration (Auto Test) / Deployment (Auto Release).
77. What is JWT?
Stateless token (Header.Payload.Signature). Verified, not stored.
78. `Object.assign` vs Spread syntax?
Similar for shallow copy. Spread is newer syntax, `Object.assign` triggers setters.
79. What is a "Race Condition"?
System behavior depends on uncontrolled timing of events.
80. Explain "Immutability".
State cannot be changed after creation. Crucial for React/Redux/Functional Programming.

⬆ Top