Javascript Interview Qns
Javascript Interview Qns
• Primitive types:
o Boolean - true/false
• Non-primitive type:
Answer:
• var: Function-scoped, can be redeclared and updated, hoisted to the top of its scope
• let: Block-scoped, can be updated but not redeclared, hoisted but not initialized
Answer: Hoisting is JavaScript's default behavior of moving declarations to the top of their containing
scope. Variable and function declarations are hoisted, but not initializations. Only the declaration is
hoisted, not the assignment.
Answer: A closure is a function that has access to its own scope, the outer function's variables, and
global variables - even after the outer function has returned. Closures are created every time a
function is created.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
console.log(counter()); // 1
console.log(counter()); // 2
Answer:
• === (strict equality) compares both value and type without type coercion
Answer: Arrow functions are a concise syntax for writing function expressions in ES6. They don't
have their own this, arguments, super, or new.target bindings, making them unsuitable for methods
or constructors.
Example:
javascript
Copy
Answer: this refers to the object that the function is a property of or the object that the function is
called on. The value of this depends on how the function is called:
• With call(), apply(), bind(): this refers to the object passed as argument
Answer:
• call(): Invokes the function with a given this value and arguments provided individually
• bind(): Returns a new function with a bound this value and optional preset arguments
Answer: Higher-order functions are functions that operate on other functions by taking them as
arguments or returning them. Examples include map(), filter(), and reduce().
Asynchronous JavaScript
Answer: The event loop is what allows JavaScript to be non-blocking and asynchronous. It
continuously checks the call stack and if it's empty, it takes the first task from the callback queue and
pushes it to the call stack. It consists of:
• Call Stack
• Web APIs
Example:
if (success) {
resolve(value);
} else {
reject(error);
});
Answer: Async/await is syntactic sugar built on top of promises that allows writing asynchronous
code that looks synchronous. An async function returns a promise, and await pauses the execution
until the promise is resolved.
Example:
try {
return data;
} catch (error) {
console.error(error);
Answer:
• setInterval() executes a function repeatedly with a fixed time delay between each call
Answer: JavaScript uses prototypal inheritance where objects can inherit properties from other
objects. Each object has a prototype object from which it inherits properties. This forms a prototype
chain until null is reached.
Answer:
• Object.create() creates a new object with the specified prototype object and properties
• The new operator creates an instance of a user-defined object type or of one of the built-in
object types that has a constructor function
Answer: Getters and setters are functions that get or set the value of an object's property. They are
defined using get and set keywords.
Example:
const obj = {
_name: '',
get name() {
return this._name;
},
set name(value) {
this._name = value;
};
ES6+ Features
Answer: Template literals are string literals allowing embedded expressions, multi-line strings, and
string interpolation using backticks (`) and ${expression}.
Example:
console.log(`Hello ${name}!`);
Answer: Default parameters allow named parameters to be initialized with default values if no value
or undefined is passed.
Example:
Answer: Destructuring assignment is a syntax that allows unpacking values from arrays or properties
from objects into distinct variables.
Example:
// Array destructuring
// Object destructuring
Error Handling
Example:
try {
} catch (error) {
console.error(error.message);
} finally {
Answer: The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It represents the page so that programs can change the document structure, style, and
content.
Answer: Event delegation is a technique where instead of adding event listeners to individual
elements, you add a single event listener to a parent element that will fire for all descendants
matching a selector, whether they exist now or are added in the future.
Answer:
• localStorage: Stores data with no expiration date, cleared only through JavaScript or clearing
browser cache
• sessionStorage: Stores data for one session (data is lost when the browser tab is closed)
Advanced Concepts
Answer: Memoization is an optimization technique where the results of expensive function calls are
cached so that when the same inputs occur again, the cached result can be returned.
Example:
javascript
Copy
function memoize(fn) {
const cache = {};
return function(...args) {
if (cache[key]) {
return cache[key];
cache[key] = result;
return result;
};
Answer: Currying is a technique of evaluating functions with multiple arguments into a sequence of
functions with single arguments.
Example:
javascript
Copy
function curry(fn) {
} else {
return function(...args2) {
};
};
27. What is the difference between shallow copy and deep copy?
Answer:
• Shallow copy: Copies only the top-level properties, nested objects are shared between
original and copy
• Deep copy: Creates a new copy of all levels of the object hierarchy
Answer: The TDZ is the period between entering scope and being declared where variables (let and
const) cannot be accessed. Attempting to access them results in a ReferenceError.
• Using console.log()
• Linting tools
Performance
This list covers a wide range of JavaScript interview questions from basic to advanced concepts. Be
prepared to explain these concepts clearly and provide practical examples during interviews.
continue
Answer: An IIFE is a function that runs as soon as it is defined. It helps create private scope and avoid
polluting the global namespace.
javascript
Copy
(function() {
console.log('This runs immediately');
})();
Answer:
• undefined means a variable has been declared but not assigned a value
• Module Pattern
• Singleton Pattern
• Factory Pattern
• Observer Pattern
• Prototype Pattern
• MVC Pattern
Answer: Web Workers allow running scripts in background threads separate from the main execution
thread, preventing UI freezing during heavy computations.
javascript
Copy
worker.postMessage(data);
worker.onmessage = function(e) {
};
Answer: Cross-Origin Resource Sharing (CORS) is a mechanism that allows restricted resources on a
web page to be requested from another domain outside the domain from which the first resource
was served.
Answer: Generators are functions that can be exited and later re-entered, with their context saved
across re-entrances. They are defined with function* and use yield to pause execution.
javascript
Copy
function* idGenerator() {
let id = 1;
while(true) {
yield id++;
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
Answer: JavaScript modules are reusable pieces of code that can be exported from one program and
imported for use in another. ES6 introduced import/export syntax.
javascript
Copy
// math.js
// app.js
Answer:
• forEach: Executes a provided function once for each array element (no return value)
• map: Creates a new array with the results of calling a provided function on every element
Answer: reduce executes a reducer function on each element of the array, resulting in a single
output value.
javascript
Copy
// sum = 6
Answer: Proxies allow you to create a proxy for another object that can intercept and redefine
fundamental operations for that object.
javascript
Copy
const handler = {
get(target, prop) {
};
p.a = 1;
console.log(p.a, p.b); // 1, 37
Answer: The void operator evaluates an expression and then returns undefined. It's often used to
obtain the undefined primitive value.
javascript
Copy
console.log('Test');
}();
// Returns undefined
Answer:
javascript
Copy
Answer: The with statement extends the scope chain for a statement. It's discouraged because:
• Slower performance
Answer:
• WeakMap: Collection of key/value pairs where keys are objects and weakly referenced
• WeakSet: Collection of objects where each object may occur only once (weakly referenced)
47. What is the difference between Array.from() and the spread operator?
Answer:
Answer:
Answer: JavaScript performs implicit type conversion when operators are applied to values of
different types. Rules include:
Answer: Tail call optimization is where a recursive function call is the last operation in the function,
allowing the engine to reuse the current stack frame instead of creating a new one. ES6 specifies
support for TCO but it's not widely implemented.
Answer:
Answer: The arguments object is an array-like object available inside functions that contains the
values of the arguments passed to that function. It's not available in arrow functions.
javascript
Copy
function sum() {
let total = 0;
total += arguments[i];
return total;
Answer: Symbols are unique and immutable primitive values that can be used as object property
keys. They help:
• Add properties to objects you don't own without risk of name collisions
Answer:
Answer: Decorators are a proposal for extending JavaScript classes and properties at design time
(currently stage 3 proposal). They use the @decorator syntax.
javascript
Copy
@log
class MyClass {
@readonly
method() {}
57. What is the difference between throw Error and throw new Error()?
Answer: There's no practical difference - both create a new Error object. throw Error() is shorthand
for throw new Error().
Answer: The finally block executes after the try and catch blocks, regardless of whether an exception
was thrown or caught. It's useful for cleanup code.
59. What are the different ways to create objects in JavaScript?
Answer:
3. Object.create()
5. Factory functions
Answer:
• instanceof: Tests whether an object has a constructor's prototype in its prototype chain
Answer: ArrayBuffer represents a fixed-length raw binary data buffer. It's used for working with
binary data directly, often in conjunction with typed arrays (Int8Array, Uint32Array, etc.)
and DataView.
Answer: The Temporal API is a new date/time API proposal for JavaScript that aims to fix problems
with the existing Date object by providing:
• Better immutability
Answer:
• globalThis: Standard way to access the global object in any environment (browsers, Node.js,
etc.)
64. What are the different ways to handle asynchronous code in JavaScript?
Answer:
1. Callbacks
2. Promises
3. Async/await
5. Event emitters
6. Observables (RxJS)
Answer: The Intl object provides language-sensitive string comparison, number formatting, and
date/time formatting through its constructors
(Intl.Collator, Intl.NumberFormat, Intl.DateTimeFormat).
Answer:
Answer: The at() method takes an integer value and returns the item at that index, allowing for
positive and negative integers (negative integers count back from the last item).
arr.at(-1); // 3
68. What is the difference between Object.assign() and the spread operator for objects?
Answer:
Answer: The ?? operator returns its right-hand side operand when its left-hand side operand
is null or undefined, otherwise returns its left-hand side operand.
70. What is the difference between ?. (optional chaining) and && for property access?
Answer:
• && operator: Checks for all falsy values (not just null/undefined)
obj?.prop; // undefined if obj is null/undefined
This comprehensive list covers fundamental to advanced JavaScript concepts that are commonly
asked in technical interviews. Being able to explain and demonstrate these concepts will significantly
improve your chances in JavaScript interviews.
DOM
1. What is the DOM?
Answer:
The Document Object Model (DOM) is a programming interface for HTML and XML documents that
represents the page as a tree of objects (nodes). JavaScript can manipulate these objects to:
• Add/remove elements
document.getElementById("myElement");
Answer:
Common selection methods:
document.getElementsByClassName("class"); // HTMLCollection
document.getElementsByTagName("div"); // HTMLCollection
document.querySelectorAll("p.highlight"); // NodeList
Answer:
Answer:
Three-step process:
// 1. Create element
// 2. Configure element
newDiv.classList.add("box");
// 3. Add to DOM
Answer:
Security Note: innerHTML can expose XSS vulnerabilities if used with untrusted content.
Answer:
Three approaches:
<button onclick="handleClick()">Click</button>
element.addEventListener("click", function(e) {
console.log("Clicked", e.target);
});
Answer:
Event delegation attaches a single event listener to a parent element to handle events from multiple
child elements. Benefits:
document.getElementById("parent").addEventListener("click", function(e) {
if(e.target.classList.contains("child")) {
});
Answer:
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM ready!");
});
window.addEventListener("load", () => {
});
Answer:
Three approaches:
element.style.backgroundColor = "#eee";
element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("visible");
element.className = "new-class";
Answer:
• parentNode: Returns any type of parent node (including text nodes, document fragments)
• parentElement: Returns only element parent nodes (null if parent isn't an element)