JavaScript Interview Questions (Fundamentals)
A comprehensive guide to JavaScript interview questions, organized by difficulty level. This collection covers fundamental concepts to advanced topics commonly asked in web development interviews.Easy Level Questions
1. What is JavaScript and where is it commonly used?
1. What is JavaScript and where is it commonly used?
- Web application development (front-end)
- Server-side development (back-end with Node.js)
- Mobile application development
- Interactive web page features
2. What are template literals in JavaScript?
2. What are template literals in JavaScript?
$, curly brackets {}, and backticks ` to make string interpolation easier and more readable.Without template literals:- Embed variables and expressions directly into strings
- Make code more readable and flexible
- Avoid complex string concatenation
3. What is hoisting? Give an example.
3. What is hoisting? Give an example.
- Function Hoisting:
- Variable Hoisting:
vardeclarations are hoisted and initialized withundefinedletandconstare hoisted but not initialized (temporal dead zone)- Function declarations are fully hoisted
4. Explain the difference between var, let, and const
4. Explain the difference between var, let, and const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function scope | Block scope | Block scope |
| Reassignment | Yes | Yes | No |
| Re-declaration | Yes | No | No |
| Hoisting | Hoisted with undefined | Hoisted but not initialized | Hoisted but not initialized |
- Avoid
vardue to its global accessibility and potential bugs - Use
constby default to prevent accidental reassignment - Use
letonly when you need to reassign values
5. What are the data types available in JavaScript?
5. What are the data types available in JavaScript?
- Number: Integer and floating-point numbers, including special values (
Infinity,-Infinity,NaN)
- String: Sequence of characters
- Boolean: Logical entity with two values
- Undefined: Default value for declared but unassigned variables
- Null: Intentional absence of value
- Symbol: Unique and immutable identifier
- BigInt: Very large integers beyond Number limit
- Object: Collection of key-value pairs
- Array: Ordered collection of values (zero-indexed)
- Function: Reusable block of code
6. What is an array in JavaScript and how do you access its elements?
6. What is an array in JavaScript and how do you access its elements?
7. Explain the difference between == and === in JavaScript
7. Explain the difference between == and === in JavaScript
| Operator | Name | Type Coercion | Example |
|---|---|---|---|
| == | Equality operator | Yes | '5' == 5 → true |
| === | Strict equality operator | No | '5' === 5 → false |
=== (strict equality) to avoid unexpected type coercion bugs.8. What is the purpose of the isNaN() function?
8. What is the purpose of the isNaN() function?
isNaN() is a special JavaScript function that checks if a given value is “Not a Number” (NaN). It returns true if the value cannot be coerced into a number.Examples:9. What is null and undefined?
9. What is null and undefined?
| Feature | undefined | null |
|---|---|---|
| Meaning | Default absence of value | Intentional absence of value |
| Assignment | Automatically assigned | Manually assigned |
| Type | undefined | object (historical bug) |
| Use case | Variable declared but not initialized | Explicitly setting “no value” |
10. Explain the use of the typeof operator
10. Explain the use of the typeof operator
typeof operator determines the data type of a given value or variable and returns a string indicating the type.Examples:- Input validation
- Conditional logic based on data types
- Debugging and type checking
Medium Level Questions
11. What is the purpose of the map() method in JavaScript?
11. What is the purpose of the map() method in JavaScript?
map() method creates a new array by applying a specified function to each element of an existing array. It doesn’t modify the original array.Example:- Concise one-line transformations
- Doesn’t mutate the original array
- Functional programming approach
- More readable than loops
12. What is event bubbling and event capturing in JavaScript?
12. What is event bubbling and event capturing in JavaScript?
- Like information flowing from CEO → Manager → Employee
- Like concerns flowing from Employee → Manager → CEO
13. What are higher-order functions? Can you give an example?
13. What are higher-order functions? Can you give an example?
- Takes another function as an argument, OR
- Returns a function as a result
map(),filter(),reduce()forEach(),find(),some(),every()setTimeout(),setInterval()
14. What is an IIFE (Immediately Invoked Function Expression) in JavaScript?
14. What is an IIFE (Immediately Invoked Function Expression) in JavaScript?
- No name needed (anonymous function)
- Executes immediately without calling
- Creates private scope (data encapsulation)
- Avoids polluting global namespace
15. What do you understand by closures in JavaScript?
15. What do you understand by closures in JavaScript?
16. How do setTimeout() and setInterval() work?
16. How do setTimeout() and setInterval() work?
setTimeout() - Execute once after delay:setInterval() - Execute repeatedly at intervals:setTimeout(): Notifications, delayed actions, debouncingsetInterval(): Clocks, real-time updates, polling APIs
17. Explain the concept of Promises in JavaScript
17. Explain the concept of Promises in JavaScript
- Pending: Initial state, neither fulfilled nor rejected
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
- Better error handling than callbacks
- Cleaner code structure
- Avoids callback hell
- Chainable operations
18. What is the use of async and await in JavaScript?
18. What is the use of async and await in JavaScript?
async/await provides a cleaner syntax for working with Promises, making asynchronous code look and behave more like synchronous code.Key Points:asyncfunction always returns a Promiseawaitpauses execution until Promise resolves- Must use
awaitinsideasyncfunction - Code continues other tasks while waiting (non-blocking)
19. What is the difference between call(), apply(), and bind()?
19. What is the difference between call(), apply(), and bind()?
this context for a function, but they differ in how they handle arguments and execution.call() - Executes immediately, arguments passed individually:apply() - Executes immediately, arguments passed as array:bind() - Returns new function, executes later:| Method | Execution | Arguments | Returns |
|---|---|---|---|
call() | Immediate | Individual | Result |
apply() | Immediate | Array | Result |
bind() | Later | Individual/Array | New function |
- call: Waiter takes orders one by one, tells chef immediately
- apply: Waiter writes all orders in a list, tells chef immediately
- bind: Waiter takes orders, tells chef to cook when ready
this refers to, avoiding confusion in complex code.20. What is event delegation?
20. What is event delegation?
- Better Performance: One listener instead of many
- Handles Dynamic Elements: Works for elements added later
- Less Memory Usage: Fewer event listeners
- Cleaner Code: Centralized event handling
Hard Level Questions
21. Explain the event loop in JavaScript
21. Explain the event loop in JavaScript
- Call Stack: Executes synchronous code
- Web APIs: Handle asynchronous operations (setTimeout, fetch, etc.)
- Task Queue: Stores completed async tasks
- Event Loop: Checks if call stack is empty, then moves tasks from queue to stack
- Chef = Main thread (call stack)
- Boiling water = Async operation
- Assistant = Event loop (checks if tasks are complete)
- “Start” executes (synchronous)
- setTimeout sends callback to Web API
- “End” executes (synchronous)
- Call stack empty → event loop moves timeout callback to stack
- “Timeout” executes
22. What is the difference between Promises and async/await?
22. What is the difference between Promises and async/await?
async/await is syntactic sugar built on top of Promises, providing cleaner syntax while Promises are the underlying mechanism.Key Differences:| Feature | Promise | Async/Await |
|---|---|---|
| Syntax | .then() chains | Try/catch blocks |
| Readability | Can get messy | Cleaner, synchronous-like |
| Error Handling | .catch() | try/catch |
| Relationship | Foundation | Built on Promises |
- Promises: Simple async operations, library compatibility
- Async/Await: Complex async flows, better readability needed
23. Describe the purpose of the reduce() method in arrays
23. Describe the purpose of the reduce() method in arrays
reduce() method reduces an array to a single value by applying a function to each element, accumulating the result.Syntax:| Step | Accumulator | Current Value | Result |
|---|---|---|---|
| 1 | 0 (initial) | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 6 | 4 | 10 |
| 5 | 10 | 5 | 15 |
- Concise (one line instead of loops)
- Functional programming approach
- Versatile (sum, average, flatten, group, etc.)
- Doesn’t mutate original array
24. Explain the concept of currying in JavaScript
24. Explain the concept of currying in JavaScript
- Template = Fixed parameter (constant)
- Animal content = Variable parameter (dynamic)
- Reusability: Fix common parameters, reuse function
- Flexibility: Create specialized functions from general ones
- Performance: Reduce redundant parameter passing
- Code Organization: Cleaner, more modular code
25. What is a generator function and how is it used?
25. What is a generator function and how is it used?
yield keyword.Syntax:- Regular: Runs completely, then returns
- Generator: Pauses at each
yield, resumes onnext()
- Lazy evaluation (compute only when needed)
- Memory efficient
- Prevents infinite loop crashes
- Useful for iterating large datasets
26. What are WeakMap and WeakSet in JavaScript?
26. What are WeakMap and WeakSet in JavaScript?
- Stores key-value pairs where keys must be objects
- Keys are weakly referenced (can be garbage collected)
- Not iterable, no
sizeproperty
- Stores unique object references
- Only accepts objects, not primitives
- Not iterable, no
sizeproperty
| Feature | Map/Set | WeakMap/WeakSet |
|---|---|---|
| Keys/Values | Any type | Objects only |
| Iteration | Iterable | Not iterable |
| Size property | Yes | No |
| Garbage Collection | Prevents GC | Allows GC |
| Use case | Permanent storage | Temporary/cache |
- Cache management: Store temporary data that can be cleaned up
- Private data: Associate metadata with objects
- Memory leaks prevention: Automatic cleanup when objects are no longer needed
27. How does JavaScript handle memory management?
27. How does JavaScript handle memory management?
- Stores primitive data types
- Fixed size, fast access
- Automatically cleaned when out of scope
- Stores non-primitive data types (objects, arrays, functions)
- Dynamic size, slower access
- Requires garbage collection
- Variables referencing
nullor out of scope are garbage collected - Memory is freed for new allocations
28. Describe the difference between shallow copy and deep copy
28. Describe the difference between shallow copy and deep copy
- Copies main properties
- Nested objects/arrays remain referenced (not copied)
- Changes to nested items affect original
- Copies everything, including nested objects
- Creates completely independent clone
- Changes don’t affect original
- Shallow Copy: Photo of a tree (change photo, tree changes - cursed photo!)
- Deep Copy: Clone of a tree (change clone, original unaffected)
| Operation | Shallow Copy | Deep Copy |
|---|---|---|
| Top-level properties | Copied | Copied |
| Nested objects | Referenced | Copied |
| Independence | Partial | Complete |
| Performance | Fast | Slower |
| Methods | {...obj}, Object.assign() | JSON.parse(JSON.stringify()) |
- Shallow: Simple objects, performance critical
- Deep: Complex nested structures, complete independence needed
29. What is JavaScript's strict mode and how is it enabled?
29. What is JavaScript's strict mode and how is it enabled?
this as Global Object:with Statement:eval():- Modern JavaScript development (always recommended)
- Prevents common mistakes
- Makes debugging easier
- Required for ES6 modules (automatic)
30. Explain the Observer pattern and how it relates to JavaScript
30. Explain the Observer pattern and how it relates to JavaScript
- Subject: Object being observed (e.g., YouTube channel)
- Observers: Objects watching the subject (e.g., subscribers)
- Notification: Mechanism to alert observers (e.g., notifications)
- Influencer (Subject) posts new content
- Subscribers (Observers) get notified
- YouTube (Platform) handles notification system
- Loose Coupling: Subject doesn’t need to know observer details
- Dynamic Relationships: Add/remove observers at runtime
- Broadcast Communication: One-to-many notifications
- Scalability: Easy to add new observers
- Event listeners (DOM events)
- State management (Redux, MobX)
- Pub/Sub systems
- Real-time updates (WebSocket notifications)