Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Thursday, July 2, 2026

250+ JavaScript Interview Questions & Answers 2026: Beginner to Expert with AI & Business Scenarios – FreeLearning365

250+ JavaScript Interview Questions & Answers 2026: Beginner to Expert with AI & Business Scenarios – FreeLearning365

🚀 250+ JavaScript Interview Questions & Answers 2026

Beginner → Most Expert • AI‑Driven Development • Real Business Scenarios • Hands‑on Labs

🌟 Master JavaScript & Land Your Dream Job!

Access the Ultimate Job Interview Preparation Portal – Programming, System Design, Soft Skills & more.

🚪 Go to Job Interview Portal

🌟 Beginner JavaScript Questions (55)

Foundational knowledge every JavaScript developer must have.

Beginner 1. What is JavaScript and where does it run?

JavaScript is a high‑level, interpreted programming language that conforms to the ECMAScript specification. It runs primarily in browsers (client‑side) and on servers via Node.js, Deno, or other runtimes.

Beginner 2. Explain the difference between var, let, and const.

var is function‑scoped, can be redeclared, hoisted with undefined. let is block‑scoped, cannot be redeclared, hoisted but not initialized. const is block‑scoped, cannot be reassigned, must be initialized.

Beginner 3. What are the primitive data types in JavaScript?

String, Number, BigInt, Boolean, undefined, null, Symbol (ES6). Objects and arrays are reference types.

Beginner 4. What is the difference between == and ===?

== performs type coercion before comparing. === compares both value and type without coercion. Always prefer strict equality.

Beginner 5. How does typeof work? Show some tricky examples.
typeof 42          // "number"
typeof "hello"     // "string"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object" (historic bug)
typeof {}          // "object"
typeof []          // "object"
typeof function(){}// "function"
Beginner 6. What is hoisting?

Hoisting is JavaScript's default behavior of moving declarations to the top of their scope during compilation. var variables are hoisted and initialized with undefined; let/const are hoisted but not initialized (Temporal Dead Zone). Function declarations are fully hoisted.

Beginner 7. How do you write a single‑line and multi‑line comment?
// single line
/* multi
   line */
Beginner 8. What are template literals?

Template literals use backticks (`) and allow embedded expressions with ${...}, multi‑line strings, and tagged templates.

const name = "John";
console.log(`Hello, ${name}!`);
Beginner 9. How do you define an array and access its elements?
const fruits = ["apple", "banana", "orange"];
console.log(fruits[1]); // "banana"
console.log(fruits.length); // 3
Beginner 10. Explain basic if...else and the ternary operator.
if (age >= 18) {
    console.log("Adult");
} else {
    console.log("Minor");
}
const status = age >= 18 ? "Adult" : "Minor";
Beginner 11. Write a for loop that logs numbers 0 to 4.
for (let i = 0; i < 5; i++) {
    console.log(i);
}
Beginner 12. What is the difference between while and do...while?

while checks condition before executing; do...while always runs at least once because condition is checked after.

Beginner 13. How do you create an object literal?
const person = {
    name: "Alice",
    age: 30,
    greet() { console.log(`Hi, I'm ${this.name}`); }
};
Beginner 14. What is a function declaration vs expression?
// Declaration (hoisted)
function add(a, b) { return a + b; }
// Expression (not hoisted)
const add = function(a, b) { return a + b; };
Beginner 15. What are arrow functions and how do they differ?

Arrow functions have shorter syntax, lexical this binding (they don't have their own this, arguments, super, or new.target).

const add = (a, b) => a + b;
Beginner 16. How do you add an element to the end and beginning of an array?
arr.push("end");   // end
arr.unshift("start"); // beginning
Beginner 17. What is NaN and how to check for it?

NaN means "Not‑a‑Number". It is the result of an invalid math operation. Use Number.isNaN(value) for reliable check.

Beginner 18. How to convert a string to a number?
Number("42");       // 42
parseInt("42px");   // 42
parseFloat("3.14"); // 3.14
+"42";              // 42 (unary plus)
Beginner 19. What is the typeof NaN?

typeof NaN returns "number". It is a numeric data type that represents an invalid number.

Beginner 20. How do you select an HTML element by ID?
const header = document.getElementById("main-header");
// or with querySelector
const header = document.querySelector("#main-header");
Beginner 21. How do you change the text content of an element?
document.getElementById("title").textContent = "New Title";
// or innerText (respects CSS) or innerHTML (for HTML)
Beginner 22. What is an event listener? Give an example.
button.addEventListener("click", () => {
    alert("Clicked!");
});
Beginner 23. How do you create a new element and append it to the DOM?
const newDiv = document.createElement("div");
newDiv.textContent = "Hello";
document.body.appendChild(newDiv);
Beginner 24. What is the difference between innerHTML and textContent?

innerHTML parses content as HTML, which can be a security risk (XSS). textContent sets/get text only, safe.

Beginner 25. How do you handle a button click to change a paragraph's color?
document.getElementById("changeBtn").addEventListener("click", () => {
    document.getElementById("myPara").style.color = "red";
});
Beginner 26. What is the window object?

In browsers, window is the global object representing the browser window. It contains methods like alert(), setTimeout(), and all global variables.

Beginner 27. How to set a timer with setTimeout and cancel it?
const timerId = setTimeout(() => console.log("Delayed"), 2000);
clearTimeout(timerId); // cancel
Beginner 28. What is setInterval and how to stop it?
const id = setInterval(() => console.log("Tick"), 1000);
clearInterval(id); // stop
Beginner 29. How do you debug JavaScript code in the browser?

Use console.log(), breakpoints in DevTools Sources panel, debugger statement, and step through execution.

Beginner 30. What is the purpose of "use strict"?

Strict mode enforces better coding practices: catches silent errors (assignment to undeclared variables), prohibits duplicate parameter names, makes this undefined in functions.

Beginner 31. How to create a multiline string in ES5?

Using string concatenation or \n escape. ES6 template literals are the modern way.

Beginner 32. What is null vs undefined?

undefined means a variable has been declared but not assigned. null is an assignment value representing "no value". typeof null is "object".

Beginner 33. How do you check if a variable is an array?
Array.isArray(value); // true if array
Beginner 34. What are the falsy values in JavaScript?

false, 0, "" (empty string), null, undefined, NaN, 0n (BigInt zero). Everything else is truthy.

Beginner 35. How do you loop over an array using forEach?
arr.forEach((item, index) => console.log(index, item));
Beginner 36. What is the difference between for...in and for...of?

for...in iterates over enumerable property names (keys). for...of iterates over iterable objects (values), like arrays.

Beginner 37. How do you add/remove a CSS class with JavaScript?
element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("dark");
Beginner 38. What is console.table()?

Displays data as a table in the console, useful for arrays of objects.

Beginner 39. How to get the current date and time?
const now = new Date();
console.log(now.toISOString());
Beginner 40. How to round a number to two decimal places?
const rounded = Math.round(num * 100) / 100;
// or
const fixed = num.toFixed(2); // string
Beginner 41. What is the Math.random() function?

Returns a floating‑point number between 0 (inclusive) and 1 (exclusive). Multiply and floor to get random integers.

Beginner 42. How do you split a string into an array?
"a,b,c".split(","); // ["a", "b", "c"]
Beginner 43. How to join an array into a string?
["a", "b", "c"].join("-"); // "a-b-c"
Beginner 44. What is the difference between slice and splice?

slice(start, end) returns a new shallow copy of a portion, original unchanged. splice(start, deleteCount, ...items) modifies the original array by removing/replacing elements.

Beginner 45. How to find the index of an element in an array?
arr.indexOf("banana");   // -1 if not found
arr.findIndex(item => item.id === 3);
Beginner 46. What does Array.prototype.map() do?

Creates a new array by calling a provided function on every element. [1,2,3].map(x => x * 2)[2,4,6].

Beginner 47. What does filter() do?

Returns a new array with elements that pass the test. [1,2,3,4].filter(x => x > 2)[3,4].

Beginner 48. What does reduce() do?

Reduces array to a single value. [1,2,3].reduce((acc, cur) => acc + cur, 0) → 6.

Beginner 49. How to copy an array (shallow)?
const copy = [...original];
// or original.slice();
Beginner 50. How to merge two arrays?
const merged = [...arr1, ...arr2];
// or arr1.concat(arr2);
Beginner 51. What is a truthy value? Give examples.

Any value that is not falsy. Examples: "hello", 42, [], {}, true.

Beginner 52. How to convert a number to a string?
String(42);    // "42"
42..toString(); // "42"
`${42}`;       // "42"
Beginner 53. What is the confirm() dialog?

Displays a modal with OK/Cancel, returns true/false. if (confirm("Are you sure?")) { ... }

Beginner 54. How to get the length of an object?
Object.keys(obj).length;
Beginner 55. How to check if an object has a property?
"key" in obj;
obj.hasOwnProperty("key");

🔵 Intermediate JavaScript Questions (65)

Deeper into closures, prototypes, async, and real‑world patterns.

Intermediate 56. Explain closures and give a practical example.

A closure is a function that remembers its lexical scope even when executed outside that scope. Example: function counter() { let count = 0; return () => ++count; } const inc = counter(); console.log(inc()); // 1. Used for data privacy, currying, event handlers.

Intermediate 57. What is the prototype chain?

Every JavaScript object has an internal [[Prototype]] link (accessed via __proto__ or Object.getPrototypeOf). When accessing a property, if not found on the object, it looks up the chain. Constructor functions have prototype property that becomes the __proto__ of instances.

Intermediate 58. How does prototypal inheritance work?
function Animal(name) { this.name = name; }
Animal.prototype.speak = function() { console.log(this.name + ' makes a sound.'); };
function Dog(name) { Animal.call(this, name); }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() { console.log('Woof!'); };
Intermediate 59. What are the differences between classical and prototypal inheritance?

Classical (class‑based) inheritance creates rigid hierarchies. Prototypal inheritance is more flexible; objects inherit directly from other objects. ES6 classes are syntactic sugar over prototypal inheritance.

Intermediate 60. Explain the this keyword and its binding rules.

this depends on call‑site: default binding (global/undefined in strict), implicit binding (object method), explicit binding (call/apply/bind), new binding (constructor), arrow functions (lexical this).

Intermediate 61. How do call(), apply(), and bind() work?

func.call(thisArg, arg1, arg2) invokes with given this. apply same but arguments as array. bind returns a new function with fixed this.

Intermediate 62. What is an IIFE and why use it?

Immediately Invoked Function Expression: (function() { ... })();. Creates a private scope to avoid polluting global namespace.

Intermediate 63. Explain the module pattern and revealing module pattern.

Uses closures to create private variables and expose a public API. Revealing module returns an object mapping public members to private functions.

const myModule = (function() {
    let privateVar = 0;
    function privateFunc() { ... }
    return { publicMethod: privateFunc };
})();
Intermediate 64. What is event bubbling and capturing?

Events propagate in two phases: capturing phase (down from root to target) and bubbling phase (up from target to root). addEventListener third parameter true makes it capture. Use event.stopPropagation() to stop.

Intermediate 65. How does event delegation work?

Attach a single event listener to a parent element and use event.target to determine which child triggered the event. Efficient for dynamic elements.

document.getElementById("list").addEventListener("click", e => {
    if (e.target.tagName === "LI") console.log(e.target.textContent);
});
Intermediate 66. What are promises and how do they improve async code?

A Promise represents an eventual completion/failure of an async operation. They avoid callback hell, allow chaining (.then()), and provide error handling with .catch().

Intermediate 67. Create a promise that resolves after 1 second.
const delay = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Done"), 1000);
});
delay.then(value => console.log(value));
Intermediate 68. How does promise chaining work? Show .then() and .catch().
fetch(url)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));
Intermediate 69. What is Promise.all() and when to use it?

Returns a single Promise that resolves when all input promises resolve, or rejects if any reject. Good for parallel independent requests.

const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
Intermediate 70. Explain Promise.race() and Promise.any().

race() settles as soon as any input settles (resolve or reject). any() resolves as soon as any resolves; rejects only if all reject.

Intermediate 71. What is async/await and how does it relate to promises?

Syntactic sugar for promises. async functions return a Promise. await pauses execution until promise settles. Makes code look synchronous.

async function getData() {
    const res = await fetch(url);
    return res.json();
}
Intermediate 72. How to handle errors with async/await?
try {
    const data = await fetchData();
} catch (err) {
    console.error(err);
}
Intermediate 73. What is the Fetch API and how to make a POST request?
fetch('/api/items', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'New Item' })
}).then(res => res.json());
Intermediate 74. What is JSON and how to parse/stringify?
const obj = JSON.parse('{"a":1}');
const str = JSON.stringify(obj);
Intermediate 75. How do you create a deep clone of an object?
const deepCopy = JSON.parse(JSON.stringify(obj)); // limitations: no functions, dates
// structuredClone (modern)
const copy = structuredClone(obj);
Intermediate 76. Explain destructuring assignment for arrays and objects.
// Array
const [a, b] = [1, 2];
// Object
const { name, age } = user;
// Nested
const { address: { city } } = user;
Intermediate 77. What is the spread/rest operator?

Spread (...) expands an iterable into individual elements. Rest collects remaining arguments into an array.

const arr = [1, 2, 3];
const newArr = [...arr, 4]; // spread
function sum(...nums) { return nums.reduce((a,b)=>a+b,0); } // rest
Intermediate 78. How do ES6 modules work? (import/export)
// module.js
export const PI = 3.14;
export function add(a,b) { return a+b; }
// default export
export default class User { ... }

// main.js
import User, { PI, add } from './module.js';
Intermediate 79. What is the difference between default and named exports?

Named exports allow multiple per module, imported with { }. Default export is unique, imported without braces. Can combine.

Intermediate 80. What are higher‑order functions?

Functions that take other functions as arguments or return functions. Examples: map, filter, reduce, and custom once(fn).

Intermediate 81. Write a function that mimics Array.prototype.map.
function map(arr, fn) {
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        result.push(fn(arr[i], i, arr));
    }
    return result;
}
Intermediate 82. What is currying? Provide an example.

Currying transforms a function with multiple arguments into a sequence of nesting functions, each taking a single argument. const add = a => b => a + b; add(2)(3) // 5.

Intermediate 83. Explain the event loop and call stack.

The call stack executes synchronous code. Async tasks (setTimeout, fetch) are handed off to Web APIs, then placed in callback queue/microtask queue. The event loop pushes callbacks onto stack when empty. Microtasks (promises, mutation observer) have higher priority than macrotasks (setTimeout).

Intermediate 84. What are microtasks and macrotasks? Give examples.

Microtasks: Promise callbacks (.then/.catch/finally), queueMicrotask, MutationObserver. Macrotasks: setTimeout, setInterval, I/O, UI rendering.

Intermediate 85. Predict the order of logs:
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);
// Output: 1, 4, 3, 2
Intermediate 86. What is debounce and throttle?

Debounce delays function execution until after a pause (e.g., search input). Throttle limits execution to once per interval (e.g., scroll). Both control high‑frequency events.

Intermediate 87. Write a simple debounce function.
function debounce(fn, delay) {
    let timer;
    return function(...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}
Intermediate 88. Write a throttle function.
function throttle(fn, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            fn.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}
Intermediate 89. What is the difference between localStorage and sessionStorage?

Both store key‑value pairs. localStorage persists across sessions; sessionStorage cleared when tab closes. Both same‑origin. Max ~5MB.

Intermediate 90. How to handle CORS errors?

CORS (Cross‑Origin Resource Sharing) is enforced by browsers. Server must respond with Access-Control-Allow-Origin header. For simple GET, you may use a proxy server or JSONP (legacy).

Intermediate 91. What is a web worker and when to use it?

Web Workers run scripts in background threads, separate from the main UI thread, allowing heavy computation without freezing the page. Communication via postMessage.

Intermediate 92. Explain Object.create() and Object.assign().

Object.create(proto) creates a new object with specified prototype. Object.assign(target, ...sources) copies enumerable own properties to target (shallow).

Intermediate 93. How to define a class with constructor and method?
class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    area() { return this.width * this.height; }
}
Intermediate 94. What are getters and setters in JavaScript?
class Circle {
    constructor(radius) { this._radius = radius; }
    get radius() { return this._radius; }
    set radius(val) { if (val > 0) this._radius = val; }
}
Intermediate 95. What is the static keyword in classes?

Defines methods/properties on the class itself, not instances. static create() { ... }.

Intermediate 96. How to implement inheritance with ES6 classes?
class Dog extends Animal {
    constructor(name, breed) {
        super(name);
        this.breed = breed;
    }
    bark() { console.log('Woof!'); }
}
Intermediate 97. What is a Symbol and why use it?

A unique and immutable primitive used as object property keys to avoid name collisions. Also used for well‑known symbols like Symbol.iterator.

Intermediate 98. Explain iterators and iterables.

An iterable has Symbol.iterator method that returns an iterator. Iterator has next() returning { value, done }. for...of uses iterables.

Intermediate 99. How to make an object iterable?
const obj = {
    data: [1,2,3],
    [Symbol.iterator]() {
        let i = 0;
        return { next: () => ({ value: this.data[i++], done: i > this.data.length }) };
    }
};
Intermediate 100. What are generators? (function*)

Generators are functions that can be paused and resumed, using yield. They return an iterator. Useful for async flow, lazy evaluation.

function* idGen() { let i=0; while(true) yield i++; }
Intermediate 101. How to use try...catch...finally?
try {
    riskyOperation();
} catch (err) {
    console.error(err);
} finally {
    cleanup();
}
Intermediate 102. What is the difference between throw and Error object?

throw raises an exception. Best practice to throw an Error instance (or subclass) for stack trace. throw new Error("msg").

Intermediate 103. How to handle rejected promises globally?
// browser:
window.addEventListener("unhandledrejection", event => { ... });
// Node:
process.on("unhandledRejection", (reason, promise) => { ... });
Intermediate 104. What is a polyfill? Give an example.

A polyfill implements missing features for older environments. Example: Array.prototype.includes polyfill.

if (!Array.prototype.includes) {
    Array.prototype.includes = function(search) { return this.indexOf(search) !== -1; };
}
Intermediate 105. How to detect if code runs in browser or Node?
typeof window !== "undefined"; // browser
typeof process !== "undefined" && process.versions?.node; // Node
Intermediate 106. What is the difference between process.nextTick() and setImmediate() in Node?

process.nextTick() fires before any other I/O events (microtask‑like but not exactly). setImmediate() fires on the next iteration of event loop (after I/O).

Intermediate 107. How to read a file in Node.js?
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
// or promises: fs.promises.readFile('file.txt', 'utf8');
Intermediate 108. What is the EventEmitter in Node.js?

A class that allows objects to emit named events and listen to them. Core pattern for many Node APIs.

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('data', (msg) => console.log(msg));
emitter.emit('data', 'Hello');
Intermediate 109. How to create a simple HTTP server in Node.js?
const http = require('http');
const server = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World');
});
server.listen(3000);
Intermediate 110. How to use Express to build a REST API?
const express = require('express');
const app = express();
app.get('/api/items', (req, res) => res.json([{ id: 1 }]));
app.post('/api/items', (req, res) => res.status(201).json(newItem));
app.listen(3000);
Intermediate 111. What is middleware in Express?

Functions that have access to request, response, and next middleware. They can modify request/response, end the cycle, or call next().

Intermediate 112. How to enable CORS in Express?
const cors = require('cors');
app.use(cors());
Intermediate 113. What is the difference between CommonJS and ES modules?

CommonJS uses require/module.exports, synchronous, dynamic. ES modules use import/export, static (mostly), asynchronous, can be tree‑shaken.

Intermediate 114. How to use environment variables in Node.js?
// set: process.env.MY_VAR = "value";
// read: console.log(process.env.MY_VAR);
// Use dotenv package for .env files
Intermediate 115. What is npm and how to initialize a project?
npm init -y   // create package.json
npm install express  // add dependency
npm install --save-dev jest  // dev dependency
Intermediate 116. What is the difference between dependencies and devDependencies?

dependencies are needed at runtime. devDependencies only for development (testing, build tools). Production install (--production) excludes devDeps.

Intermediate 117. How to implement a basic JWT authentication in Node?
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
// verify: jwt.verify(token, secret);
Intermediate 118. What are Map and Set?

Map holds key‑value pairs and remembers insertion order; keys can be any type. Set stores unique values of any type. Both have useful methods.

Intermediate 119. How does the Proxy object work?
const target = {};
const handler = { get(obj, prop) { return prop in obj ? obj[prop] : 42; } };
const proxy = new Proxy(target, handler);
console.log(proxy.foo); // 42
Intermediate 120. What is Reflect API?

Provides methods for interceptable JavaScript operations. Used in proxy traps for default behavior. E.g., Reflect.get(target, prop).

🟣 Expert JavaScript Questions (55)

Expert 121. Explain the JavaScript engine (V8) compilation pipeline.

V8 parses JS → AST, interprets (Ignition) with feedback, compiles hot functions with TurboFan (optimizing compiler). Uses hidden classes and inline caching for performance.

Expert 122. What are hidden classes and inline caching?

V8 creates hidden classes (maps) to represent object shapes. When properties are added in the same order, objects share hidden class, enabling fast property access via inline caching.

Expert 123. How does memory management work (garbage collection)?

JavaScript uses automatic GC: Mark‑and‑Sweep. Objects not reachable from roots are freed. V8 has generational (new/old space) and incremental GC to minimize pauses.

Expert 124. How to avoid memory leaks? Common causes?

Global variables, forgotten timers, detached DOM nodes, closures holding large objects, event listeners not removed. Use WeakMap for caches.

Expert 125. What is a WeakMap and WeakSet? Why use them?

They hold "weak" references to objects; objects can be garbage collected if only held weakly. Keys in WeakMap must be objects. Useful for caching data attached to an object without preventing GC.

Expert 126. How to implement a custom Promise from scratch?
class MyPromise {
    constructor(executor) {
        this.state = 'pending';
        this.value = undefined;
        this.callbacks = [];
        const resolve = val => {
            if (this.state !== 'pending') return;
            this.state = 'fulfilled'; this.value = val;
            this.callbacks.forEach(cb => cb.onFulfilled(val));
        };
        // reject similar...
        executor(resolve, reject);
    }
    then(onFulfilled, onRejected) { ... }
}
Expert 127. What is the difference between Object.freeze() and Object.seal()?

freeze prevents adding, deleting, or changing properties. seal prevents adding/deleting but allows modifying existing property values.

Expert 128. How to make a deep freeze function?
function deepFreeze(obj) {
    Object.keys(obj).forEach(key => {
        if (typeof obj[key] === 'object' && !Object.isFrozen(obj[key])) deepFreeze(obj[key]);
    });
    return Object.freeze(obj);
}
Expert 129. Explain the requestAnimationFrame API and why it’s better than setInterval for animations.

It schedules a function to run before next repaint, syncing with display refresh rate. Saves battery, pauses when tab inactive, smoother animations.

Expert 130. What are Service Workers and their use cases?

A proxy between web app and network. Enables offline support, background sync, push notifications. Runs on separate thread. Requires HTTPS.

Expert 131. How does the async/await behave in loops? (forEach vs for...of)

forEach does not wait for promises; it calls async callback but doesn't await them. for...of with await pauses each iteration.

Expert 132. What is a Proxy trap for negative array indices?
new Proxy([], { get(target, prop) { let idx = Number(prop); if (idx < 0) idx = target.length + idx; return target[idx]; } });
Expert 133. How to implement memoization?
function memoize(fn) {
    const cache = new Map();
    return function(arg) {
        if (cache.has(arg)) return cache.get(arg);
        const result = fn(arg);
        cache.set(arg, result);
        return result;
    };
}
Expert 134. Explain the concept of "tagged templates".

A function that processes template literals. First argument is array of string segments, rest are substitutions. E.g., styled‑components, GraphQL queries.

function tag(strings, ...values) { return strings[0] + values[0].toUpperCase(); }
const result = tag`hello ${'world'}`; // "hello WORLD"
Expert 135. What is the Temporal Dead Zone (TDZ)?

The time between entering scope and variable declaration where let/const cannot be accessed. Access throws ReferenceError.

Expert 136. How to implement a pub/sub pattern?
const eventBus = {
    listeners: {},
    on(event, cb) { (this.listeners[event] ||= []).push(cb); },
    emit(event, data) { this.listeners[event]?.forEach(cb => cb(data)); }
};
Expert 137. How does the new operator work internally?
  1. Creates new empty object.
  2. Links its __proto__ to constructor's prototype.
  3. Binds this to new object and calls constructor.
  4. Returns the object (unless constructor returns an object).
Expert 138. Implement Object.create polyfill.
if (!Object.create) {
    Object.create = function(proto) {
        function F() {}
        F.prototype = proto;
        return new F();
    };
}
Expert 139. How to implement a simple dependency injection container?
class Container {
    constructor() { this.services = new Map(); }
    register(name, factory) { this.services.set(name, factory); }
    resolve(name) { const factory = this.services.get(name); return factory(this); }
}
Expert 140. 🤖 AI How to integrate OpenAI API in a Node.js backend?
const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: [...] })
});
const data = await response.json();
Expert 141. How to use TensorFlow.js to run a pre‑trained model in browser?
const model = await tf.loadGraphModel('model.json');
const tensor = tf.tensor(inputData);
const result = model.execute(tensor);
console.log(result.dataSync());
Expert 142. Explain the differences between JavaScript and TypeScript.

TypeScript adds static typing, interfaces, generics, enums, and better tooling, but compiles to JavaScript. It helps catch errors early.

Expert 143. What is tree‑shaking?

Dead‑code elimination performed by bundlers (Webpack, Rollup) that removes unused exports from ES modules, reducing bundle size.

Expert 144. How to lazy load a module?
// dynamic import
const module = await import('./module.js');
module.doSomething();
Expert 145. What is the Intl API?

Internationalization API: formatting dates, numbers, currencies, collation. E.g., new Intl.DateTimeFormat('de-DE').format(date).

Expert 146. How to measure performance of a function?
console.time('myFunc');
myFunc();
console.timeEnd('myFunc');
// or performance.now()
Expert 147. What are decorators? (TC39 proposal)

Functions that modify classes/methods/properties. Used in TypeScript. Still stage 3. Can add metadata, logging, etc.

Expert 148. How to securely handle user input to prevent XSS?

Encode output, avoid innerHTML, use textContent or DOM APIs. Sanitize with DOMPurify. Set Content‑Security‑Policy headers.

Expert 149. Explain the difference between defer and async on script tags.

async downloads in parallel and executes immediately; order not guaranteed. defer downloads in parallel but executes after HTML parsing, in order.

Expert 150. What is the Intersection Observer API?

Asynchronously observe when an element enters/leaves viewport or another element. Efficient for lazy loading, infinite scroll, ad visibility.

const obs = new IntersectionObserver(entries => { ... });
obs.observe(element);
Expert 151. How to implement a simple virtual DOM?

Represent DOM as plain JS objects. Diff old and new tree, compute minimal patches, apply to real DOM. Key concepts: hyperscript, reconciliation.

Expert 152. What is eval() and why is it dangerous?

Executes arbitrary code from string, allowing injection attacks, performance issues (prevents optimization). Avoid it.

Expert 153. How to use structuredClone to clone complex objects?
const copy = structuredClone(original);
Handles circular references, Date, Map, Set, ArrayBuffer, but not functions.
Expert 154. What is the queueMicrotask() function?

Queues a microtask directly, like Promise.resolve().then(cb) but more explicit.

Expert 155. How to implement a rate limiter in Node.js for API?
const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }));
Expert 156. What is the difference between process.stdout.write and console.log?

console.log adds newline, is synchronous in terminal but async in pipes; process.stdout.write writes raw without newline.

Expert 157. How does Node.js cluster module work?

Fork multiple worker processes that share the same server port. Master distributes incoming connections. Uses cluster.fork().

Expert 158. What is Buffer in Node.js?

Represents fixed‑size raw binary data. Used for I/O, streams. Buffer.from('hello').

Expert 159. How to stream a large file response in Express?
const readStream = fs.createReadStream('bigfile.mp4');
readStream.pipe(res);
Expert 160. Explain the pipe() method in streams.

Chains readable stream to writable stream, handling backpressure automatically. readable.pipe(writable).

Expert 161. What is the difference between fork and spawn in Node child processes?

spawn runs a command with streams; fork is special for running Node modules with IPC channel.

Expert 162. How to implement GraphQL server with Apollo Server?
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql` type Query { hello: String } `;
const resolvers = { Query: { hello: () => 'world' } };
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => console.log(url));
Expert 163. What is a reactive programming? How does RxJS work?

Reactive programming deals with asynchronous data streams. RxJS uses Observables (push‑based) with operators to compose async operations.

Expert 164. How to build a CLI tool with Node.js?

Create package with bin field in package.json. Use commander or yargs to parse arguments.

Expert 165. How to use AbortController to cancel fetch?
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort(); // cancels request
Expert 166. What are SharedArrayBuffer and Atomics?

Allow sharing memory across web workers and performing atomic operations, enabling low‑level concurrency.

Expert 167. How to implement a polyfill for Promise.allSettled()?
Promise.allSettled = promises => Promise.all(promises.map(p => Promise.resolve(p).then(value => ({status:'fulfilled', value}), reason => ({status:'rejected', reason}))));
Expert 168. What is the BigInt type?

Represents integers beyond the safe Number range (2⁵³-1). Append n: const big = 9007199254740991n;. Cannot mix with Number.

Expert 169. How to handle floating‑point precision issues?

Use toFixed() for display, multiply then divide, or use libraries like decimal.js.

Expert 170. Explain the ?. optional chaining operator.

user?.address?.city returns undefined if any intermediate is null/undefined instead of throwing error. Also func?.(), arr?.[0].

Expert 171. What is the nullish coalescing operator (??)?

value ?? default returns right‑hand side only if left is null or undefined (not other falsy values).

Expert 172. How does logical assignment work? (||=, &&=, ??=)

x ||= y sets x to y if x falsy. x &&= y sets if truthy. x ??= y if null/undefined. Short‑circuit evaluation.

Expert 173. What is the # private field syntax in classes?

Truly private fields (not accessible outside class) using #fieldName. Example: class Counter { #count = 0; increment() { this.#count++; } }.

Expert 174. How to use Array.prototype.at()?

Returns element at index, supports negative integers (from end). arr.at(-1) gets last element.

Expert 175. Explain the difference between sort() with and without compare function.

Without compare, elements converted to strings and sorted lexicographically (may give unexpected results for numbers). Provide (a,b) => a-b for numeric.

🔴 Most Expert / Architect (45)

Architect 176. How does V8 optimize object property access (hidden classes)?

When properties are added in a consistent order, objects share a hidden class (Map). V8 can use inline caching to directly access property at fixed offset. Dynamically adding properties in different orders creates multiple maps, causing deoptimization.

Architect 177. How to prevent deoptimization in hot functions?

Keep object shapes consistent (add properties in constructor), avoid delete, use same argument types, avoid arguments object, prefer monomorphic function calls.

Architect 178. What is the role of TurboFan and how does it use type feedback?

TurboFan is V8's optimizing compiler. Ignition collects type feedback (which types were seen). TurboFan speculatively optimizes based on that; if assumptions fail, it deoptimizes back to Ignition.

Architect 179. How does the event loop differ in Node.js? (phases)

Node event loop has phases: timers, pending callbacks, idle/prepare, poll (I/O), check (setImmediate), close callbacks. Microtasks run between each phase.

Architect 180. Explain the libuv library and its thread pool.

libuv provides event loop and async I/O operations. For blocking operations (file system, DNS), it uses a thread pool (default 4 threads). You can increase with UV_THREADPOOL_SIZE.

Architect 181. How to implement a worker pool to offload CPU‑intensive tasks?

Use Node worker_threads. Create workers, communicate via postMessage. Use a pool library like piscina for efficient reuse.

Architect 182. What is the async_hooks module used for?

Tracks asynchronous resource lifecycle (promises, timers) for diagnostics, context propagation, performance monitoring.

Architect 183. How to build a custom context propagation (like AsyncLocalStorage)?
const { AsyncLocalStorage } = require('async_hooks');
const als = new AsyncLocalStorage();
als.run({ requestId }, () => { /* all async operations here have access */ });
Architect 184. How to implement a distributed tracing system with JavaScript?

Use OpenTelemetry JS SDK. Create spans, propagate context via headers (W3C TraceContext). Export to Jaeger/Zipkin.

Architect 185. What are microservices communication patterns in Node.js? (message broker)

Use RabbitMQ, Kafka, or Redis pub/sub. Use libraries like amqplib or kafkajs. Implement event‑driven with guaranteed delivery.

Architect 186. How to design a high‑throughput REST API with Node.js?

Use non‑blocking I/O, cluster module, async/await, connection pooling, caching (Redis), avoid blocking operations, use streams for large data, load‑balance across processes.

Architect 187. What is the reactor pattern and how does Node.js use it?

Node uses event demultiplexing (libuv) to wait for I/O events, then invokes callbacks. Single‑threaded event loop but scalable.

Architect 188. How to implement a custom duplex stream?
const { Duplex } = require('stream');
const myDuplex = new Duplex({
    write(chunk, encoding, cb) { this.push(chunk); cb(); },
    read(size) { /* ... */ }
});
Architect 189. How to handle backpressure in Node.js streams manually?

When write() returns false, pause the source. Listen to 'drain' event to resume. pipe() does this automatically.

Architect 190. 🤖 AI How to build a real‑time AI chatbot with Node.js, WebSocket, and OpenAI streaming?

Use WebSocket (ws) for duplex connection. When user sends message, stream OpenAI response chunks via fetch with response.body.getReader(), forward each chunk over WebSocket.

Architect 191. How to implement server‑sent events with Node.js and reconnection?
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' });
const id = setInterval(() => res.write(`data: ${JSON.stringify(data)}\n\n`), 1000);
req.on('close', () => clearInterval(id));
Architect 192. How to use graphql‑ws for subscriptions?

Set up a WebSocket server, use graphql‑ws protocol with ws. Apollo Server supports it via subscriptions-transport-ws or graphql-ws.

Architect 193. How to prevent prototype pollution attacks?

Avoid deep merge without safe checks. Use Object.create(null) for maps. Freeze Object.prototype. Validate keys against __proto__, constructor. Use libraries like lodash.set with safety.

Architect 194. What is new Function() and its security implications?

Creates a function from string. Has access to global scope, can be exploited for code injection. Strict CSP mitigates. Prefer safer alternatives.

Architect 195. How to implement a content‑security policy in a Node.js app?
app.use((req, res, next) => {
    res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'");
    next();
});
Architect 196. How does React’s reconciliation algorithm work? (Virtual DOM diffing)

Compares old and new virtual trees, uses heuristics (type, key) to update real DOM efficiently. Batching updates. Key for list stability.

Architect 197. What is the difference between a framework like React and vanilla JS for complex UIs?

Framework provides declarative rendering, state management, efficient DOM updates, and component model. Vanilla requires manual imperative DOM updates, harder to maintain at scale.

Architect 198. How to implement a state management library like Redux from scratch?
function createStore(reducer) {
    let state;
    const listeners = [];
    const getState = () => state;
    const dispatch = action => { state = reducer(state, action); listeners.forEach(l => l()); };
    const subscribe = listener => { listeners.push(listener); return () => listeners.filter(l => l !== listener); };
    dispatch({ type: '@@INIT' });
    return { getState, dispatch, subscribe };
}
Architect 199. How to implement a JavaScript module bundler basics?

Parse entry file, resolve imports, build dependency graph, wrap each module in a function with require and module cache, concatenate into one bundle. Webpack/Rollup do this with optimizations.

Architect 200. What is the Shadow DOM and how does it relate to Web Components?

Encapsulates markup and styles for a component. element.attachShadow({mode:'open'}) creates a shadow tree. Web Components use it for isolation.

Architect 201. How to implement a custom element?
class MyElement extends HTMLElement {
    connectedCallback() { this.innerHTML = `

Hello

`; } } customElements.define('my-element', MyElement);
Architect 202. What is WebAssembly and how to call it from JavaScript?

WASM is a binary instruction format for high‑performance code in browser/Node. Load .wasm via WebAssembly.instantiate, then call exported functions.

Architect 203. How to profile memory usage and find leaks in Node.js?

Use --inspect flag with Chrome DevTools, take heap snapshots, compare. Or process.memoryUsage(), v8.getHeapStatistics(). Use clinic doctor.

Architect 204. What is the difference between fs.stat and fs.access?

stat retrieves metadata (size, permissions). access tests if file is accessible with specified mode (read/write).

Architect 205. How to implement a circuit breaker for external API calls?
class CircuitBreaker {
    constructor(fn, options) { /* state: closed, open, halfOpen */ }
    async call(...args) { /* if open, reject fast; else try, on error increment failures */ }
}
Architect 206. 🤖 AI How to use LangChain.js to build an agent that uses tools?
import { initializeAgentExecutorWithOptions } from 'langchain/agents';
const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: 'zero-shot-react-description' });
const result = await executor.call({ input: 'What is the weather?' });
Architect 207. Explain the concept of "Isomorphic/Universal JavaScript".

Code that runs both on client and server, e.g., React SSR. Allows initial render on server, then client hydration.

Architect 208. How to implement a GraphQL federation gateway with JavaScript?

Use @apollo/gateway and @apollo/server. Define subgraphs, build supergraph schema, execute queries across services.

Architect 209. What is the BroadcastChannel API?

Allows communication between browsing contexts (tabs, iframes) of the same origin. const bc = new BroadcastChannel('test'); bc.postMessage('hello');.

Architect 210. How to implement a simple static file server with caching (ETag)?

Calculate ETag from file stats (size + mtime). On request, check If-None-Match. If match, return 304. Else serve file.

Architect 211. What are the benefits of using Fastify over Express?

Faster due to optimized schema‑based serialization, built‑in validation, lower overhead. Good for high throughput APIs.

Architect 212. How to handle graceful shutdown in Node.js?
process.on('SIGTERM', () => {
    server.close(() => {
        // close DB connections, etc.
        process.exit(0);
    });
});
Architect 213. How to implement JSON Web Encryption (JWE)?

Use jose library. Encrypt payload with compactEncrypt, decrypt with compactDecrypt. Provides confidentiality, not just signing.

Architect 214. What is the difference between console.trace and a debugger?

console.trace prints stack trace to console. Debugger allows stepping, inspection, breakpoints.

Architect 215. How does the JavaScript engine handle tail call optimization?

ES6 specifies tail call optimization (TCO) to reuse stack frame for tail calls. Only Safari/JSC implement it; V8 removed due to implementation complexity.

Architect 216. What is a Proxy with construct trap? Show example.
const Handler = { construct(target, args) { return new target(...args); } };
const ProxiedClass = new Proxy(MyClass, Handler);
new ProxiedClass();
Architect 217. How to create a true singleton in JavaScript?
const singleton = (() => { let instance; return () => { if (!instance) instance = new MyClass(); return instance; }; })();
Architect 218. How to use Symbol.hasInstance to customize instanceof?
class MyArray {
    static [Symbol.hasInstance](instance) { return Array.isArray(instance); }
}
Architect 219. What is the import.meta object?

Exposes context‑specific metadata about the current module, like import.meta.url. In browsers, import.meta.resolve (proposal).

Architect 220. How to implement a custom iterator using generators? [Symbol.iterator]
const obj = {
    *[Symbol.iterator]() { yield 1; yield 2; yield 3; }
};

💼 Business Problem Scenarios (15)

Scenario 1: An e‑commerce checkout page needs to handle real‑time shipping cost calculation based on address. Solution: Use fetch with debounce on zip code input, call backend API, update UI. Cache responses with Map.
Scenario 2: A social media feed must load posts infinitely. Solution: Implement infinite scroll with Intersection Observer. Load next page via AJAX, append to DOM. Use throttle to avoid redundant calls.
Scenario 3: Need to support offline editing of a document and sync when online. Solution: Use Service Worker + IndexedDB. Queue changes, detect online, sync using Background Sync API.
Scenario 4: A dashboard with multiple real‑time charts from WebSocket. Solution: Use a single WebSocket connection with multiplexing. Each chart subscribes to specific topic; on message, update chart instance.
Scenario 5: Build a search autocomplete with suggestions from API. Solution: Debounce input, call backend, render dropdown. Use AbortController to cancel previous requests on new keystroke.
Scenario 6: A Node.js API must process a large CSV upload without blocking. Solution: Stream the upload to disk, parse CSV with streams (csv‑parser), insert rows in batches using async iteration, send progress via SSE.
Scenario 7: Need to log all API requests with response time and user ID. Solution: Middleware in Express that records start time, calls next(), then calculates duration, writes to log file or external service.
Scenario 8: User uploads an image that needs resizing before storing. Solution: Use sharp (Node.js) or Canvas API (browser) to resize. Offload to worker thread if heavy.
Scenario 9: A real‑time collaborative whiteboard application. Solution: Use WebSocket server (Socket.IO), broadcast drawing commands, maintain state on server or use CRDT for conflict resolution.
Scenario 10: Implement a JWT authentication flow with silent refresh. Solution: Store access token in memory, refresh token in httpOnly cookie. On 401, use Axios interceptor to attempt refresh, retry request.
Scenario 11: Need to measure web performance and report Core Web Vitals. Solution: Use web‑vitals library, send data to analytics via navigator.sendBeacon().
Scenario 12: Building a multi‑step form with state preservation across steps. Solution: Use React Context or Redux, validate each step, save to localStorage, restore on reload.
Scenario 13: 🤖 AI Add a smart reply suggestion feature in a chat app using AI. Solution: Send last few messages to OpenAI API, get completion, display suggestions. Cache frequent contexts.
Scenario 14: Protect against excessive API usage by implementing client‑side rate limiting. Solution: Use token bucket algorithm on client; wait if tokens exhausted. Backend also enforces limits.
Scenario 15: Migrate a legacy jQuery app to a modern framework incrementally. Solution: Use micro‑frontends approach: embed new components (React/Vue) via custom elements or iframes, share routing gradually.

🧪 Hands‑on Labs (10)

Lab 1: Build a complete CRUD To‑Do app with vanilla JS (DOM + localStorage).

Create UI, store tasks in array, render list. Save to localStorage. Add edit/delete functionality.

Lab 2: Implement a Promise‑based HTTP client with fetch and interceptors.

Wrap fetch with pre‑request/post‑response hooks. Add retry on failure.

Lab 3: Create a custom EventEmitter class with on, once, emit, off.

Store listeners in Map. once wrapper that auto‑removes.

Lab 4: Build a simple Express API with MongoDB and JWT auth.

Set up Mongoose models, CRUD routes, register/login, protect routes with middleware.

Lab 5: Write a Node.js script that recursively reads all files in a directory and counts lines.

Use fs.readdir, stat, and readline interface. Async/await.

Lab 6: Implement a debounced search input that fetches results from an API and displays them.

HTML input, listen to input, debounce 300ms, fetch, render results.

Lab 7: 🤖 AI Create a simple chatbot interface that streams responses from OpenAI API.

Use fetch with stream: true parameter (if available) or SSE endpoint. Update UI incrementally.

Lab 8: Build a real‑time notification system with Socket.IO.

Client connects to server, server emits events, client shows toast notification.

Lab 9: Write unit tests for a utility module using Jest.

Create math.js, write test file with test cases for add, subtract, mock dependencies.

Lab 10: Containerize a Node.js app with Docker and compose with Redis.

Write Dockerfile, docker-compose.yml, add Redis for session store.

📝 Code‑Based Challenges (12)

Challenge 1: Implement a function that flattens a nested array to any depth.
function flatten(arr, depth = 1) {
    return depth > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val, depth-1) : val), []) : arr.slice();
}
Challenge 2: Write a function that returns a memoized version of a Fibonacci calculator.
function memoFib() {
    const cache = {};
    return function fib(n) {
        if (n in cache) return cache[n];
        if (n <= 1) return n;
        return cache[n] = fib(n-1) + fib(n-2);
    };
}
Challenge 3: Implement a custom bind function.
Function.prototype.myBind = function(context, ...args) {
    const fn = this;
    return function(...rest) { return fn.apply(context, [...args, ...rest]); };
};
Challenge 4: Create a deep clone function that handles Date, Map, Set, and circular references.

Use a WeakMap to track already cloned objects, recursive descent. For other built‑ins, use custom logic.

Challenge 5: Write a Promise.all polyfill.
function promiseAll(promises) {
    return new Promise((resolve, reject) => {
        let resolvedCount = 0;
        const results = [];
        promises.forEach((p, i) => Promise.resolve(p).then(val => { results[i] = val; resolvedCount++; if (resolvedCount === promises.length) resolve(results); }, reject));
    });
}
Challenge 6: Implement an async function that runs tasks in series with a concurrency limit.

Use a queue, track active tasks, start new when one finishes, up to limit.

Challenge 7: 🤖 AI Call OpenAI to classify text sentiment, with error retry.
const fetchWithRetry = (url, opts, retries=3) => fetch(url, opts).catch(err => retries>0 ? fetchWithRetry(url, opts, retries-1) : Promise.reject(err));
Challenge 8: Implement a simple reactive state system (like Vue's reactivity).
function reactive(obj) {
    return new Proxy(obj, { set(target, prop, value) { target[prop] = value; /* notify watchers */ return true; } });
}
Challenge 9: Build a throttle function that also returns the last call after throttle ends (trailing).
function throttle(fn, limit) {
    let lastCall, timer;
    return function(...args) {
        const now = Date.now();
        if (!lastCall || now - lastCall >= limit) { fn.apply(this, args); lastCall = now; } else {
            clearTimeout(timer);
            timer = setTimeout(() => { fn.apply(this, args); lastCall = Date.now(); }, limit - (now - lastCall));
        }
    };
}
Challenge 10: Write a function that converts a callback‑based function to a Promise (promisify).
function promisify(fn) {
    return (...args) => new Promise((resolve, reject) => fn(...args, (err, result) => err ? reject(err) : resolve(result)));
}
Challenge 11: Implement an EventEmitter with wildcard listeners (on('*', ...)).

In emit, invoke wildcard listeners passing event name along with data.

Challenge 12: Create a function that batches multiple identical requests within a short window.

Collect requests, debounce, then send single batched request, distribute responses to original callers.

🔥 Ready to crack your JavaScript interview?

Visit the Ultimate Job Interview Preparation Portal for full programming, system design & soft skills training.

🚪 Go to Job Interview Portal

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam