\n P Element\n
\nProgramming
JavaScript ইন্টারভিউ প্রশ্ন
Closures, prototypes, async, the event loop and ES features.
৩৬৮টি প্রশ্ন
- 1.
What is an error object?
প্রাথমিকAn error object is a built in error object that provides error information when an error occurs. It has two properties: name and message.
Example:
try { greeting("Welcome"); } catch(err) { console.log(err.name + ": " + err.message); } // Output ReferenceError: greeting is not defined⚝ Try this example on CodeSandbox
↥ back to top
- 2.
What is the difference between get and defineProperty?
প্রাথমিকBoth has similar results until unless you use classes. If you use
getthe property will be defined on the prototype of the object whereas usingObject.defineProperty()the property will be defined on the instance it is applied to.↥ back to top
- 3.
What is the use of stopPropagation method?
প্রাথমিকThe
stopPropagationmethod is used to stop the event from bubbling up the event chain.For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1)
<p>Click DIV1 Element</p> <div onclick="secondFunc()">DIV 2 <div onclick="firstFunc(event)">DIV 1</div> </div> <script> function firstFunc(event) { alert("DIV 1"); event.stopPropagation(); } function secondFunc() { alert("DIV 2"); } </script>↥ back to top
- 4.
What are the recommendations to create new object?
প্রাথমিকIt is recommended to avoid creating new objects using
new Object(). Instead you can initialize values based on it is type to create the objects.- Assign {} instead of new Object()
- Assign "" instead of new String()
- Assign 0 instead of new Number()
- Assign false instead of new Boolean()
- Assign [] instead of new Array()
- Assign /()/ instead of new RegExp()
- Assign function (){} instead of new Function()
Example:
let obj1 = {}; let obj2 = ""; let obj3 = 0; let obj4 = false; let obj5 = []; let obj6 = /()/; let obj7 = function(){};↥ back to top
- 5.
What is event capturing?
প্রাথমিকEvent capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.
Example:
<article id="ancestor"> Article Element <div id="parent"> DIV Element <p id="child"> P Element </p> </div> </article> <script> // Script to click event handler to capture on each element for (let elem of document.querySelectorAll("*")) { elem.addEventListener( "click", (e) => console.log("Capturing:", elem.tagName), true ); } </script>⚝ Try this example on CodeSandbox
↥ back to top
- 6.
What is the purpose of clearTimeout method?
প্রাথমিকThe
clearTimeout()function is used in javascript to clear the timeout which has been set bysetTimeout()function before that. i.e, The return value of setTimeout() function is stored in a variable and it\'s passed into theclearTimeout()function to clear the timer.For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method.
// clearTimeout() var msg; function greeting() { console.log("Hello World!"); stop(); } function start() { console.log("start"); msg = setTimeout(greeting, 3000); } function stop() { console.log("stop"); clearTimeout(msg); } start(); // Output Start Hello World! Stop⚝ Try this example on CodeSandbox
↥ back to top
- 7.
What is the use of setTimeout?
প্রাথমিকThe
setTimeout()method is used to call a function or evaluates an expression after a specified number of milliseconds.Syntax:
setTimeout(callback function, delay in milliseconds)Example:
setTimeout(() => { console.log("Delayed for 1 second."); }, "1000")↥ back to top
- 8.
What is a unary function?
প্রাথমিকUnary function (i.e. monadic) is a function that accepts exactly one argument. It stands for single argument accepted by a function.
// Unary function const unaryFunction = (number) => number + 10; console.log(unaryFunction(10)); // 20⚝ Try this example on CodeSandbox
↥ back to top
- 9.
What is the 'this keyword' and how does its context change?
প্রাথমিকIn JavaScript, the context of `this` refers to the execution context, typically an object that owns the function where
thisis used.'this' in the Global Scope
In non-strict mode,
thisin the global scope refers to thewindowobject. In strict mode,thisisundefined.'this' in Functions
In non-arrow functions, the value of
thisdepends on how the function is invoked. When invoked:- As a method of an object:
thisis the object. - Alone: In a browser,
thisiswindoworglobalin Node.js. In strict mode, it'sundefined. - With
call,apply, orbind:thisis explicitly set. - As a constructor (with
new):thisis the newly created object.
'this' in Arrow Functions
Arrow functions have a fixed context for
thisdefined at function creation and are not changed by how they are invoked.- They do not have their own
this. - They use the
thisfrom their surrounding lexical context (the enclosing function or global context).
Code Example: Global Context
Here is the JavaScript code:
// Main let globalVar = 10; function globalFunction() { console.log('Global this: ', this.globalVar); console.log('Global this in strict mode: ', this); } globalFunction(); // Output: 10, window or undefined (in strict mode) // In Node.js, it will be different, because "window" is not defined. But "this" will refer to the global object. - As a method of an object:
- 10.
What is recursion in JavaScript?
প্রাথমিকRecursion is a technique in which a function calls itself until it reaches a base case (a condition that stops further calls). Every recursive function must have a base case to avoid infinite loops and stack overflow errors.
Example 01: Factorial
function factorial(n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); // recursive call } console.log(factorial(5)); // 120 (5 × 4 × 3 × 2 × 1) console.log(factorial(0)); // 1Example 02: Fibonacci
function fibonacci(n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } console.log(fibonacci(6)); // 8 (0, 1, 1, 2, 3, 5, 8)Example 03: Flatten a nested array
function flattenArray(arr) { return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []); } console.log(flattenArray([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]Recursion vs Iteration:
- Recursion is more readable for tree/graph traversal, nested structures, and divide-and-conquer problems
- Iteration is more performant for simple loops — use it when recursion depth could be large
Note: For deeply nested structures, iterative solutions with an explicit stack are preferred over recursion to avoid stack-overflow errors.
↥ back to top
- 11.
What is the output of below spread operator array?
প্রাথমিক[...'Hello']Output: ['H', 'e', 'l', 'l', 'o']
Explanation: The string is an iterable type and the spread operator with in an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array.
↥ back to top
- 12.
What is class expression in es6 class?
প্রাথমিকA class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class\'s body. However, it can be accessed via the name property.
Example:
// Unnamed Class let Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }; console.log(Rectangle.name); // Rectangle // Named Class let Triangle = class TriangleClass { constructor(base, height) { this.base = base; this.height = height; } }; console.log(Triangle.name); // TriangleClass⚝ Try this example on CodeSandbox
↥ back to top
- 13.
Name the two functions that are used to create an HTML element dynamically?
প্রাথমিকIn an HTML document, the
document.createElement()method creates the HTML element specified by tagName.Syntax:
const element = document.createElement(tagName[, options]);HTML
<!DOCTYPE html> <html> <head> <title>||Working with elements||</title> </head> <body> <div id="app">The text above has been created dynamically.</div> </body> </html>JavaScript
document.body.onload = addElement; function addElement () { // create a new div element var newDiv = document.createElement("div"); var newContent = document.createTextNode("Hi there and greetings!"); // add the text node to the newly created div newDiv.appendChild(newContent); // add the newly created element and its content into the DOM var currentDiv = document.getElementById("app"); document.body.insertBefore(newDiv, currentDiv); }Create Dynamic Button:
// Create a button let btn = document.createElement("BUTTON"); btn.innerHTML = "CLICK ME"; document.body.appendChild(btn);Removing Elements Dynamically:
// Removes an element from the document function removeElement(elementId) { let element = document.getElementById(elementId); element.parentNode.removeChild(element); }⚝ Try this example on CodeSandbox
↥ back to top
- 14.
What is generator in JS?
প্রাথমিকGenerator-Function:
A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the
yieldkeyword rather thanreturn. Theyieldstatement suspends function\'s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the lastyieldrun.Syntax:
function* gen() { yield 1; yield 2; yield 3; ... }Generator-Object:
Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a "for in" loop.
Example:
// Generate Function function* fun() { yield 10; yield 20; yield 30; } // Calling the Generate Function var gen = fun(); // returns a Generator object (doesn\'t run yet) gen.next(); // { value: 10, done: false } gen.next(); // { value: 20, done: false } gen.next(); // { value: 30, done: false } gen.next(); // { value: undefined, done: true }⚝ Try this example on CodeSandbox
↥ back to top
- 15.
What is event handling in javascript?
প্রাথমিকThe change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
Some of the HTML event handlers are:
Mouse events:
|Event Handler |Description
onclick When mouse click on an element onmouseover When the cursor of the mouse comes over the element onmouseout When the cursor of the mouse leaves an element onmousedown When the mouse button is pressed over the element onmouseup When the mouse button is released over the element onmousemove When the mouse movement takes place. Form events:
Event Handler Description onfocus When the user focuses on an element onsubmit When the user submits the form onblur When the focus is away from a form element onchange When the user modifies or changes the value of a form element Window/Document events:
Event Handler Description onload When the browser finishes the loading of the page onunload When the visitor leaves the current webpage, the browser unloads it onresize When the visitor resizes the window of the browser Example: Click Event
<!DOCTYPE html> <html> <head> <script> function greeting() { alert("Hello! Good morning"); } </script> </head> <body> <h2>Click Event Example</h2> <button type="button" onclick="greeting()">Click me</button> </body> </html>⚝ Try this example on CodeSandbox
↥ back to top
- 16.
What is an Iterator?
প্রাথমিকAn iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a
.next()method which returns an object with two properties:- value: The next value in the iteration sequence.
- done: This is true if the last value in the sequence has already been consumed.
Example:
// custom Iterator function numbers() { let n = 0; return { next: function () { n += 10; return { value: n, done: false }; } }; } // Create an Iterator const number = numbers(); console.log(number.next()); // {value: 10, done: false} console.log(number.next()); // {value: 20, done: false} console.log(number.next()); // {value: 30, done: false}⚝ Try this example on CodeSandbox
↥ back to top
- 17.
What is Babel and how does transpilation work?
প্রাথমিকBabel is a JavaScript transpiler (source-to-source compiler) that converts modern JavaScript (ES6+) into a backwards-compatible version for older browsers or environments that don\'t support the latest syntax.
How it works:
- Parse — Source code is parsed into an AST (Abstract Syntax Tree).
- Transform — Plugins traverse and modify the AST (e.g. convert arrow functions to regular functions).
- Generate — The modified AST is printed back to JavaScript source code.
Installation:
npm install --save-dev @babel/core @babel/cli @babel/preset-env`babel.config.json`:
{ "presets": [ ["@babel/preset-env", { "targets": "> 0.25%, not dead", "useBuiltIns": "usage", "corejs": 3 }] ], "plugins": ["@babel/plugin-transform-class-properties"] }Example transformation:
// Input (ES6+) const greet = name => `Hello, ${name}!`; const [a, b, ...rest] = [1, 2, 3, 4]; // Output (ES5) "use strict"; var greet = function greet(name) { return "Hello, " + name + "!"; }; var _ref = [1, 2, 3, 4], a = _ref[0], b = _ref[1], rest = _ref.slice(2);Polyfills vs. transpilation:
- Transpilation handles syntax (arrow functions, destructuring, classes).
- Polyfills (
core-js,regenerator-runtime) handle missing runtime APIs (Promise,Array.from, generators).
↥ back to top
- 18.
What are static methods and properties, and how do they differ from instance members?
প্রাথমিকThe primary difference lies in where the data lives and what owns it:
- Instance methods: Belong to individual objects created via
new. Each object gets its own copy of the data.
- Static methods: Belong to the class itself. There is only one copy shared across the entire application, and you do not need to create an object to use them.
Access Memory Inherited via Static method/property ClassName.method()One copy on the class ChildClass.__proto__Instance method instance.method()Shared on prototypeinstance.__proto__Instance property instance.propOne copy per instance Own property Example:
/** * Instance methods vs static methods */ class Counter { static count = 0; // static — shared across all instances constructor(name) { this.name = name; // instance — unique per object Counter.count++; } static reset() { Counter.count = 0; // access via class name, not `this` } } const a = new Counter('a'); const b = new Counter('b'); console.log(Counter.count); // 2 — static, belongs to the class console.log(a.name); // 'a' — instance, belongs to the object // console.log(a.count); // undefined — statics aren't on instances Counter.reset(); console.log(Counter.count); // 0↥ back to top
- Instance methods: Belong to individual objects created via
- 19.
What are the various statements in error handling?
প্রাথমিকBelow are the list of statements used in an error handling,
- try: This statement is used to test a block of code for errors
- catch: This statement is used to handle the error
- throw: This statement is used to create custom errors.
- finally: This statement is used to execute code after try and catch regardless of the result.
Example:
function errorHandling() { const message = document.getElementById("app"); message.innerHTML = ""; let x = document.getElementById("app").value; try { if (x === "") throw "is empty"; if (isNaN(x)) throw "is not a number"; x = Number(x); if (x > 10) throw "is too high"; if (x < 5) throw "is too low"; } catch (err) { message.innerHTML = "Error: " + err + "."; } finally { document.getElementById("app").value = ""; } } errorHandling(); // Error: is not a number.⚝ Try this example on CodeSandbox
↥ back to top
- 20.
What is a conditional operator in javascript?
প্রাথমিকThe conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement.
Syntax:
<condition> ? <value1> : <value2>;Example:
const isAuthenticated = false; console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated');↥ back to top