1. What is JavaScript and how does it work?
JavaScript is a high-level, interpreted programming language used to make web pages interactive. It works by executing code inside the JavaScript engine (such as V8 in Chrome). JavaScript interacts with HTML and CSS through the DOM (Document Object Model) to update content dynamically without reloading the page.
2. Is JavaScript synchronous or asynchronous?
JavaScript is single-threaded and synchronous by default, meaning it executes code line by line. However, it can handle asynchronous operations using callbacks, promises, and async/await with the help of the event loop, allowing non-blocking behavior.
3. What is the difference between var, let, and const?
var is function-scoped and allows redeclaration. let and const are block-scoped. Variables declared with let can be reassigned, while const variables cannot be reassigned after initialization.
4. What is hoisting in JavaScript?
Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope during the compilation phase. Variables declared with var are hoisted and initialized as undefined, while let and const are hoisted but not initialized.
5. What is the Temporal Dead Zone (TDZ)?
The Temporal Dead Zone (TDZ) is the time between entering a block scope and the declaration of a variable using let or const. Accessing the variable inside this zone results in a ReferenceError because the variable has not been initialized yet.
6. What is the difference between == and ===?
The == operator compares values after performing type coercion, whereas === compares both value and type without type conversion. Using === is recommended to avoid unexpected results.
7. What is the difference between null and undefined?
null represents an intentional absence of value and is
explicitly assigned by the developer. undefined means a
variable has been declared but not assigned a value. Interestingly,
typeof null returns "object", which is a known
JavaScript bug.
8. What is NaN and how do you check it?
NaN stands for "Not a Number" and represents an invalid numeric result, such as dividing a number by a non-numeric value. To check NaN safely, use Number.isNaN(), as the global isNaN() function may produce incorrect results due to type coercion.
9. What is typeof and what are its limitations?
typeof is an operator used to determine the data type of a
variable. Its limitations include returning "object" for
null and being unable to distinguish between arrays and
objects. To check arrays, Array.isArray() should be used.
10. What are JavaScript data types?
JavaScript has two main categories of data types: primitive
and non-primitive. Primitive types include
String, Number, Boolean,
Undefined, Null, Symbol, and
BigInt. Non-primitive types include Object,
Array, and Function.
11. What is scope in JavaScript?
Scope in JavaScript defines the accessibility or visibility of variables, functions, and objects in different parts of the code. JavaScript mainly has global scope, function scope, and block scope.
12. What is lexical scope?
Lexical scope means that a variable’s scope is determined by its position in the source code. Inner functions can access variables defined in their outer (parent) functions because of lexical scoping.
13. What is a closure?
A closure is a function that remembers and can access variables from its outer scope even after the outer function has finished execution. Closures are created every time a function is defined inside another function.
14. Why are closures useful?
Closures are useful for data encapsulation, creating private variables, maintaining state between function calls, and implementing patterns like currying, memoization, and module design.
15. What is a memory leak in JavaScript?
A memory leak occurs when memory that is no longer needed is not released. This usually happens due to unused references, global variables, detached DOM elements, or forgotten timers and event listeners.
16. How can you prevent memory leaks?
Memory leaks can be prevented by clearing timers, removing event listeners, avoiding unnecessary global variables, properly handling closures, and releasing references to unused DOM elements.
17. What is garbage collection in JavaScript?
Garbage collection is an automatic memory management process in JavaScript where the engine frees memory occupied by objects that are no longer reachable or referenced in the program.
18. What is block scope?
Block scope restricts variable access to the block in which they are
defined, such as inside { }. Variables declared with
let and const follow block scope, unlike
var.
19. What happens if you access a variable before declaration?
Accessing a variable declared with let or const
before its declaration results in a ReferenceError due to
the Temporal Dead Zone (TDZ). With var, the value will be
undefined because of hoisting.
20. What is shadowing in JavaScript?
Shadowing occurs when a variable declared in an inner scope has the same name as a variable in an outer scope, causing the inner variable to override the outer one within that scope.
21. What is the this keyword?
The this keyword refers to the object that is executing the
current function. Its value depends on how the function is called, such as
global context, object method, constructor, or explicit binding using
call, apply, or bind.
22. How does this behave in arrow functions?
Arrow functions do not have their own this. Instead, they
inherit this from their surrounding lexical scope, making
them useful in callbacks where preserving the parent context is required.
23. Difference between normal function and arrow function?
Normal functions have their own this, arguments,
and can be used as constructors. Arrow functions have a shorter syntax,
do not bind their own this or arguments, and
cannot be used as constructors.
24. What are higher-order functions?
Higher-order functions are functions that either accept other functions as
arguments or return a function as their result. Examples include
map, filter, and reduce.
25. What is a callback function?
A callback function is a function passed as an argument to another function and executed later. Callbacks are commonly used for asynchronous operations such as API calls, event handling, and timers.
26. What is function currying?
Function currying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. This improves reusability and readability.
27. What is function composition?
Function composition is the process of combining multiple functions to produce a new function, where the output of one function becomes the input of the next. It promotes clean, modular, and reusable code.
28. What is an IIFE?
An IIFE (Immediately Invoked Function Expression) is a function that is executed immediately after it is defined. It is commonly used to create a private scope and avoid polluting the global namespace.
29. What is the arguments object?
The arguments object is an array-like object available in
normal functions that contains all passed arguments. It is not available
in arrow functions, where the rest operator should be used instead.
30. What is the rest operator?
The rest operator (...) allows a function to accept an
indefinite number of arguments as an array. It is commonly used to handle
variable-length arguments in a clean and modern way.
31. What is an object in JavaScript?
An object in JavaScript is a collection of key-value pairs used to store related data and functionality. Objects can contain properties and methods and are fundamental building blocks for structuring complex data.
32. How do you create objects in JavaScript?
Objects can be created using object literals
({}), the new Object() constructor,
constructor functions, Object.create(), or ES6
class syntax.
33. What is prototype?
A prototype is an object from which other objects inherit properties and methods. Every JavaScript object has an internal link to a prototype, enabling shared behavior and memory efficiency.
34. What is prototypal inheritance?
Prototypal inheritance is a mechanism where an object inherits properties and methods directly from another object through the prototype chain, rather than using classes as in traditional OOP.
35. Difference between Object.create() and constructor functions?
Object.create() creates a new object with a specified
prototype directly, while constructor functions use the
new keyword to create objects and assign the prototype via
the constructor’s prototype property.
36. What is the prototype chain?
The prototype chain is a sequence of objects linked through their
prototypes. When a property is not found on an object, JavaScript looks
up the chain until it reaches null.
37. Difference between classical and prototypal inheritance?
Classical inheritance is based on classes and instances, while prototypal inheritance is based on objects inheriting directly from other objects. JavaScript natively uses prototypal inheritance.
38. What is __proto__?
__proto__ is an accessor property that points to an object’s
internal prototype. It allows access to the prototype chain but is
generally discouraged in favor of Object.getPrototypeOf().
39. How does inheritance work in JavaScript?
Inheritance in JavaScript works through the prototype chain, where objects can access properties and methods of their prototype. ES6 classes provide a cleaner syntax over this underlying mechanism.
40. How do ES6 classes work internally?
ES6 classes are syntactic sugar over JavaScript’s prototypal inheritance. Internally, they use constructor functions and prototype chaining, making class-based code easier to read while preserving JavaScript’s core behavior.
41. What is asynchronous JavaScript?
Asynchronous JavaScript allows operations like API calls, timers, and file handling to run in the background without blocking the main execution thread. This enables JavaScript to remain responsive while performing time-consuming tasks.
42. What is the event loop?
The event loop is a mechanism that continuously checks the call stack and task queues to decide what code should be executed next. It enables JavaScript to handle asynchronous operations efficiently.
43. What is the call stack?
The call stack is a data structure that keeps track of function execution. Functions are added to the stack when called and removed once execution is completed. JavaScript executes code in a single-threaded call stack.
44. What is the callback queue?
The callback queue (or task queue) stores callbacks from asynchronous
operations like setTimeout and DOM events. These callbacks
are executed only after the call stack is empty.
45. What is the microtask queue?
The microtask queue holds high-priority tasks such as resolved Promises
(.then, .catch) and
MutationObserver callbacks. Microtasks are executed before
tasks in the callback queue.
46. Difference between callback queue and microtask queue?
The callback queue processes tasks like timers and events, while the microtask queue processes Promise callbacks. Microtasks always have higher priority and are executed before the callback queue after the call stack is cleared.
47. What are Promises?
Promises are objects that represent the eventual completion or failure of an asynchronous operation. They help manage asynchronous code in a more readable and maintainable way compared to callbacks.
48. What are Promise states?
A Promise has three states: pending (initial state), fulfilled (operation completed successfully), and rejected (operation failed).
49. Difference between Promises and callbacks?
Callbacks can lead to deeply nested code known as callback hell, whereas Promises provide a cleaner and more structured approach to handling asynchronous logic, along with better error handling and chaining.
50. What is async/await?
async/await is syntactic sugar built on top of Promises that
allows asynchronous code to be written in a synchronous-looking manner,
making it easier to read, write, and debug.
51. What are Web APIs?
Web APIs are browser-provided interfaces that allow JavaScript to interact with the browser and external systems. Examples include DOM API, Fetch API, Geolocation API, LocalStorage, Timers, and Web Workers.
52. What is setTimeout and setInterval?
setTimeout executes a function once after a specified delay,
while setInterval repeatedly executes a function at fixed
time intervals. Both are Web APIs and do not block the main thread.
53. What is fetch()?
fetch() is a modern Web API used to make HTTP requests. It
returns a Promise and provides a cleaner and more flexible alternative
to older request mechanisms like XMLHttpRequest.
54. Difference between fetch and XMLHttpRequest?
fetch is Promise-based and easier to use, while
XMLHttpRequest uses callbacks and has a more complex API.
Fetch also supports streaming and modern JavaScript features.
55. What is CORS?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls how resources from one origin can be requested by another origin. It prevents unauthorized access to resources across different domains.
56. What is event bubbling?
Event bubbling is a phase where an event starts from the target element and propagates upward through its parent elements to the root of the DOM.
57. What is event capturing?
Event capturing is the opposite of bubbling, where the event flows from the root of the DOM down to the target element before reaching it.
58. What is event delegation?
Event delegation is a technique where a single event listener is attached to a parent element to handle events for multiple child elements using event bubbling. It improves performance and memory usage.
59. What is preventDefault()?
preventDefault() stops the browser’s default behavior for an
event, such as preventing form submission or stopping a link from
navigating.
60. What is stopPropagation()?
stopPropagation() prevents an event from propagating further
through the DOM tree, stopping both bubbling and capturing phases.
61. What is debouncing?
Debouncing is a technique used to delay the execution of a function until a certain amount of time has passed since the last event occurred. It is commonly used for search inputs, resize events, and form validations to reduce unnecessary function calls.
62. What is throttling?
Throttling ensures that a function is executed at most once in a specified time interval, regardless of how many times the event is triggered. It is often used for scroll, resize, and mouse movement events.
63. Difference between debouncing and throttling?
Debouncing delays execution until events stop firing, while throttling limits execution to fixed intervals. Debouncing is ideal for input-based actions, whereas throttling is better for continuous events like scrolling.
64. How do you optimize JavaScript performance?
JavaScript performance can be optimized by minimizing DOM manipulations, using debouncing and throttling, avoiding memory leaks, splitting code, lazy loading resources, and using efficient algorithms and data structures.
65. What causes slow JavaScript execution?
Slow JavaScript execution can be caused by heavy computations on the main thread, excessive DOM operations, memory leaks, inefficient loops, large bundle sizes, and blocking synchronous code.
66. How does browser rendering work?
Browser rendering involves parsing HTML to build the DOM, parsing CSS to build the CSSOM, combining them into a render tree, calculating layout, painting pixels, and finally compositing layers on the screen.
67. What is repaint and reflow?
Reflow occurs when the layout of elements changes, affecting their size or position. Repaint happens when visual styles like color change without affecting layout. Reflows are more expensive than repaints.
68. What is lazy loading?
Lazy loading is a performance optimization technique where resources such as images, scripts, or components are loaded only when they are needed, reducing initial load time and improving Core Web Vitals.
69. How does code splitting work?
Code splitting breaks a large JavaScript bundle into smaller chunks that are loaded on demand. This improves performance by reducing initial load time and is commonly used with modern bundlers like Webpack and Vite.
70. What is tree shaking?
Tree shaking is a build-time optimization technique that removes unused code from JavaScript bundles. It relies on ES module syntax to eliminate dead code and reduce bundle size.
71. What are ES6 features?
ES6 (ECMAScript 2015) introduced major enhancements to JavaScript, including
let and const, arrow functions, classes, modules,
template literals, destructuring, default parameters, promises, and the
spread and rest operators, making JavaScript more powerful and readable.
72. What are template literals?
Template literals are strings enclosed in backticks (`) that
allow embedded expressions using ${}. They support multi-line
strings and improve string formatting compared to traditional concatenation.
73. What is destructuring?
Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables, making code cleaner and more expressive.
74. What are default parameters?
Default parameters allow function parameters to have predefined values
if no argument or undefined is passed, helping avoid manual
checks inside functions.
75. What is the spread operator?
The spread operator (...) expands iterable elements such as
arrays or objects into individual values. It is commonly used for copying,
merging arrays or objects, and passing arguments to functions.
76. What is the rest operator?
The rest operator (...) collects multiple values into a single
array. It is mainly used in function parameters to handle variable numbers
of arguments in a clean way.
77. What are modules?
Modules allow JavaScript code to be split into reusable files. Each module has its own scope and can export and import functionality, improving code organization and maintainability.
78. Difference between import and require?
import is part of ES modules and is statically analyzed at
compile time, while require is used in CommonJS and is
dynamically loaded at runtime. Import is preferred in modern JavaScript.
79. What is optional chaining?
Optional chaining (?.) allows safe access to deeply nested
object properties without throwing errors if a reference is
null or undefined.
80. What is nullish coalescing?
Nullish coalescing (??) returns the right-hand value only when
the left-hand value is null or undefined. Unlike
the logical OR operator, it does not treat 0 or empty strings
as falsy.
81. What will be the output of console.log(typeof null)?
The output will be "object". This is a well-known bug in
JavaScript that has existed since its early versions. Although
null represents an empty value, its type is incorrectly
reported as object.
82. What will be the output of [] + []?
The output will be an empty string "". When arrays are added,
JavaScript converts them to strings using toString(), and both
empty arrays become empty strings before concatenation.
83. What will be the output of 0.1 + 0.2 === 0.3?
The output will be false. This happens due to floating-point
precision issues in JavaScript, where 0.1 + 0.2 evaluates to
0.30000000000000004.
84. What will be the output of console.log(this)?
The output depends on context. In the global scope (browser),
this refers to the window object. Inside a function,
it depends on how the function is called. In strict mode, it can be
undefined.
85. What will be the output of setTimeout(fn, 0)?
The function fn will execute after the current call stack is
cleared. Even with a delay of 0, setTimeout is asynchronous and
is placed in the callback queue, not executed immediately.
86. What happens when you use delete on array elements?
The delete operator removes the element but does not reindex the
array. This leaves an empty slot and the array length remains unchanged,
which can cause unexpected behavior.
87. What happens when you compare two objects?
Objects are compared by reference, not by value. Even if two objects have
identical properties, comparing them with == or
=== returns false unless they reference the same
object.
88. What happens when you use the new keyword?
The new keyword creates a new object, sets its prototype to the
constructor’s prototype, binds this to the new object, and
returns it unless the constructor explicitly returns another object.
89. What happens if you forget the new keyword?
Without new, the constructor function behaves like a regular
function. In non-strict mode, this refers to the global object,
causing unintended side effects. In strict mode, it results in
undefined or an error.
90. What is the output of chained promises?
Chained promises execute sequentially, where the resolved value of one
.then() is passed to the next. The final output depends on the
values returned in each then block, and errors propagate to the
nearest catch().