0% found this document useful (0 votes)
0 views31 pages

JavaScript Interview Questions Web Dev Mastery

The document outlines important JavaScript interview questions categorized into basic, intermediate, and advanced levels. It covers fundamental concepts such as data types, hoisting, closures, and the event loop, as well as more complex topics like promises, generators, and memory management. Each section includes key definitions and examples to illustrate the concepts.

Uploaded by

Kuvarji Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views31 pages

JavaScript Interview Questions Web Dev Mastery

The document outlines important JavaScript interview questions categorized into basic, intermediate, and advanced levels. It covers fundamental concepts such as data types, hoisting, closures, and the event loop, as well as more complex topics like promises, generators, and memory management. Each section includes key definitions and examples to illustrate the concepts.

Uploaded by

Kuvarji Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Web Dev Mastery

"JavaScript Most Important Interview Questions"

Basic Level:
1. What is JavaScript? How is it different from Java?
2. Explain the difference between var, let, and const.
3. What are the data types in JavaScript?
4. What is hoisting in JavaScript?
5. What are closures in JavaScript?
6. What is the difference between == and === in JavaScript?
7. Explain how this keyword works in JavaScript.
8. What is an event in JavaScript? How do you prevent default behavior?
9. What are arrow functions, and how are they different from regular
functions?
10. What is NaN in JavaScript? How do you check if a value is NaN?

Intermediate Level:
1. What is the difference between synchronous and asynchronous
programming in JavaScript?
2. Explain the concept of promises in JavaScript.
3. What are callback functions? How are they used?
4. What are JavaScript prototypes and how do they work?
5. What is the event loop in JavaScript? How does it work with asynchronous
code?
6. Explain how map(), filter(), and reduce() functions work.
7. What is the purpose of async and await in JavaScript?
8. How does JavaScript handle memory management and garbage collection?
9. What is the debounce function in JavaScript? How is it different from
throttle?
10. What is destructuring in JavaScript? Provide examples of array and object
destructuring.

Advanced Level:
1. Explain the concept of event delegation in JavaScript.
2. What are generators in JavaScript, and how do they differ from regular
functions?
3. What are JavaScript modules, and how do you use import and export?
4. What is the Proxy object in JavaScript, and what are its use cases?
5. Explain currying in JavaScript.
6. What are the differences between deep cloning and shallow cloning in
JavaScript? How would you implement both?
7. What is memoization, and how would you implement it in JavaScript?
8. Explain the concept of weak maps and weak sets in JavaScript.
9. What is the difference between function declarations and function
expressions?
10. What is a JavaScript Symbol, and when would you use it?
11. How does the apply, call, and bind methods work in JavaScript? Provide
examples.
12. What is the purpose of the async iterator, and how does it differ from a
regular iterator?
13. How can you prevent object mutation in JavaScript?
14. Print all elements of the nested array arr = [1, [2, [3, 4], 5], 6].
15. Reverse Words in a String In JavaScript.
16. Check for Balanced Parentheses.
17. Remove Duplicates from an Array.
18. Find the Largest Sum of Contiguous Subarray (Kadane’s Algorithm)
19. Find the First Non-Repeated Character in a String
20. Given an array of n consecutive integers from 1 to n, where one integer is
missing, write a JavaScript function to find the missing number with a time
complexity of O(n).
Basic Level:
1. What is JavaScript? How is it different from Java?

● JavaScript is a lightweight, interpreted programming language primarily used for


enhancing interactivity on websites. It is a core technology of the World Wide Web,
alongside HTML and CSS.
● Differences from Java:
○ Type: Java is a statically typed, compiled language, while JavaScript is a
dynamically typed, interpreted language.
○ Syntax: Java uses class-based object-oriented programming, while JavaScript
uses prototype-based object-oriented programming.
○ Execution Environment: Java runs on the Java Virtual Machine (JVM), while
JavaScript runs in web browsers or on servers (like Node.js).

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

● var:
○ Function-scoped or globally scoped.
○ Can be re-declared and updated.
● let:
○ Block-scoped.
○ Can be updated but not re-declared in the same scope.
● const:
○ Block-scoped.
○ Cannot be updated or re-declared. However, it can hold mutable objects.
3. What are the data types in JavaScript?

JavaScript has two main categories of data types:

● Primitive Data Types:


○ Undefined: A variable that has been declared but has not been assigned a
value.
○ Null: Represents a deliberate non-value.
○ Boolean: Represents a logical entity and can have two values: true and false.
○ Number: Represents both integer and floating-point numbers.
○ BigInt: An arbitrary precision integer.
○ String: Represents a sequence of characters.
○ Symbol: A unique and immutable value often used as object property keys.
● Reference Data Types:
○ Object: A collection of key-value pairs.
○ Array: A special type of object used to store lists of values.
○ Function: A callable object.

4. What is hoisting in JavaScript?

● Hoisting is a JavaScript mechanism where variables and function declarations are


moved to the top of their containing scope during the compile phase. This means you
can use variables and functions before they are declared in the code.
5. What are closures in JavaScript?

● A closure is a function that retains access to its outer scope, even when the function is
executed outside that scope. Closures are created every time a function is created,
allowing for data encapsulation.

6. What is the difference between == and === in JavaScript?

● == (Abstract Equality Operator):


○ Performs type coercion if the operands are of different types.
○ Example: 0 == '0' evaluates to true.
● === (Strict Equality Operator):
○ Checks for both value and type without coercion.
○ Example: 0 === '0' evaluates to false.

7. Explain how the this keyword works in JavaScript.

● The this keyword refers to the context in which a function is called. Its value is
determined by how the function is invoked:
○ In a method, it refers to the object the method is called on.
○ In a regular function, it refers to the global object (or undefined in strict mode).
○ In an arrow function, this is lexically inherited from the enclosing scope.

8. What is an event in JavaScript? How do you prevent default behavior?


● An event is an action or occurrence that happens in the browser, such as clicks, key
presses, or page loads. You can prevent the default behavior of an event using the
event.preventDefault() method.

9. What are arrow functions, and how are they different from regular
functions?

● Arrow functions are a more concise syntax for writing function expressions. They differ
from regular functions in several ways:
○ Do not have their own this context (inherited from the enclosing scope).
○ Cannot be used as constructors (i.e., cannot use the new keyword).
○ Do not have the arguments object.

10. What is NaN in JavaScript? How do you check if a value is NaN?

● NaN stands for "Not-a-Number" and indicates that a value is not a valid number. It is a
special numeric value resulting from invalid mathematical operations (like dividing zero
by zero).

You can check if a value is NaN using the isNaN() function or Number.isNaN() for a more
reliable check.
Intermediate Level:
1. What is the difference between synchronous and asynchronous
programming in JavaScript?

● Synchronous programming means that tasks are executed one after the other. Each
task must finish before the next one starts. This can block the execution if a task takes a
long time.
● Asynchronous programming allows tasks to run concurrently. This means that while
one task is waiting (like fetching data), other tasks can continue executing without
waiting.

Example of Synchronous Code:

Example of Asynchronous Code:


2. Explain the concept of promises in JavaScript.

● A promise is an object that represents the eventual completion (or failure) of an


asynchronous operation and its resulting value. It allows you to write cleaner code
without nesting multiple callbacks.

States of a Promise:

● Pending: The initial state, neither fulfilled nor rejected.


● Fulfilled: The operation completed successfully.
● Rejected: The operation failed.

Example of a Promise:

3. What are callback functions? How are they used?


● A callback function is a function that is passed as an argument to another function and
is executed after some operation has been completed. This is commonly used in
asynchronous programming.

Example of a Callback Function:

4. What are JavaScript prototypes and how do they work?

● Prototypes are a mechanism by which JavaScript objects inherit features from one
another. Every JavaScript object has a prototype object from which it can inherit
properties and methods.

Example of Prototypes:
5. What is the event loop in JavaScript? How does it work with
asynchronous code?

● The event loop is a mechanism that allows JavaScript to perform non-blocking


operations despite being single-threaded. It manages the execution of code, collects and
processes events, and executes queued sub-tasks.
● When asynchronous tasks (like fetching data) are completed, their callbacks are added
to the callback queue. The event loop continuously checks the call stack and the
callback queue to execute tasks.

Illustration of the Event Loop:

1. Call Stack: Where functions are executed.


2. Web APIs: For handling asynchronous tasks (like setTimeout, fetch).
3. Callback Queue: Holds the callbacks from completed asynchronous tasks.
4. Event Loop: Checks if the call stack is empty, then moves the first callback from the
callback queue to the call stack.
6. Explain how map(), filter(), and reduce() functions work.

● These are higher-order functions for manipulating arrays:

map(): Creates a new array by applying a function to each element of the original array.
Example:

filter(): Creates a new array with all elements that pass the test implemented by the
provided function.
Example:

reduce(): Executes a reducer function on each element of the array, resulting in a single
output value.
Example:

7. What is the purpose of async and await in JavaScript?

● async and await are used to work with promises in a more readable way.
● async is a keyword that you can place before a function declaration to indicate that the
function will return a promise.
● await is used inside an async function to pause execution until the promise is
resolved.
Example:

8. How does JavaScript handle memory management and garbage


collection?

● JavaScript has automatic memory management, which means that developers do not
need to manually allocate and free memory.
● Garbage Collection is the process of automatically reclaiming memory that is no longer
in use. It tracks objects that are no longer referenced in the code and frees their memory.
● JavaScript primarily uses mark-and-sweep garbage collection, where it marks
reachable objects and sweeps away unmarked (unreachable) objects.

9. What is the debounce function in JavaScript? How is it different from


throttle?

Debounce

Main Definition: Debounce ensures that a function is executed only after a specified time has
passed since it was last invoked. This is helpful when you want to avoid running a function too
frequently, such as during user input.

Real-Life Example: Imagine you are typing in a search box. You don’t want to search every
time a letter is typed; instead, you want the search to occur after you stop typing for a moment.
Code Example:

Throttle

Main Definition: Throttle ensures that a function is executed at most once in a specified period
of time. This is useful for events that can occur continuously, such as scrolling or resizing a
window.

Real-Life Example: Think about a traffic light. It changes color at set intervals, regardless of
whether cars are still arriving. Throttling means allowing an action to happen at a limited rate.

Code Example:
Summary

● Debounce: "Only search when I’m done typing!" It waits until you stop typing for a
specified time before executing the search function.
● Throttle: "You can only drive this fast!" It limits how often a function can be executed,
ensuring it runs at most once every specified interval.

10. What is destructuring in JavaScript? Provide examples of array and


object destructuring.

● Destructuring is a syntax that allows you to unpack values from arrays or properties
from objects into distinct variables.
Array Destructuring Example:

Object Destructuring Example:


Advanced Level:

1. Explain the concept of event delegation in JavaScript.

● Event delegation is a technique where you attach a single event listener to a parent
element instead of multiple listeners to individual child elements. This improves
performance and simplifies event handling, especially when dealing with dynamically
added elements.

Example:

2. What are generators in JavaScript, and how do they differ from regular
functions?

● Generators are a special type of function that can pause and resume execution. They
are defined using the function* syntax and use the yield keyword to return values
one at a time.
● Regular functions run to completion when called, while generators can yield multiple
values over time.
Example of a Generator:

3. What are JavaScript modules, and how do you use import and export?

● JavaScript modules allow you to break your code into separate files, making it easier to
manage and reuse. You can export functions, objects, or variables from one module and
import them into another.

Export Example:

Import Example:
4. What is the Proxy object in JavaScript, and what are its use cases?

Definition: A Proxy is a JavaScript object that allows you to create a wrapper around another
object, enabling you to intercept and redefine fundamental operations for that object. This
includes property access, assignment, enumeration, and function invocation. Proxies are useful
for implementing custom behaviors such as logging, validation, and more.

Real-Life Example: Bank Account

Let's consider a bank account system where you want to track deposits and withdrawals for
security purposes. By using a Proxy, you can log these actions whenever they occur.

Definitions of get and set

● get: Intercepts property access, allowing you to define custom behavior when reading a
property.
● set: Intercepts property assignment, enabling you to define custom behavior when
updating a property.

Code Example

Here's how you could implement a simple bank account with a Proxy:
5. Explain currying in JavaScript.

● Currying is a functional programming technique where a function is transformed into a


sequence of functions, each taking a single argument. This allows you to create more
reusable and configurable functions.

Example:
6. What are the differences between deep cloning/copy and shallow
cloning/copy in JavaScript? How would you implement both?

● Shallow Cloning creates a new object but only copies the references of nested objects,
not the actual objects. Changes to nested objects in the clone affect the original object.

Shallow Clone Example:

● Deep Cloning creates a new object and recursively copies all objects and values,
meaning that changes to nested objects in the clone do not affect the original object.

Deep Clone Example:


7. What is memoization, and how would you implement it in JavaScript?

● Memoization is an optimization technique used to speed up functions by caching their


results based on input arguments. If the function is called again with the same
arguments, it returns the cached result instead of recalculating it.

Example:

8. Explain the concept of weak maps and weak sets in JavaScript.

● WeakMap and WeakSet are collections that allow you to store objects weakly. This
means that if there are no other references to the objects stored in a WeakMap or
WeakSet, they can be garbage collected, preventing memory leaks.
● WeakMap: Stores key-value pairs where keys are objects and values can be any type.
● WeakSet: Stores unique objects (no primitive values).

Example of WeakMap:
Example of WeakSet:

Real-Life Analogy:

● Imagine you have a sticky note (the object) that you temporarily attach to a fridge
(WeakMap/WeakSet). Once you no longer need the note, you can throw it away.
Similarly, WeakMap/WeakSet will automatically remove the object when it’s no longer
needed or referenced.

WeakMap and WeakSet are particularly useful in cases where you want to manage objects
without worrying about memory leaks, such as managing DOM elements or caching data for
objects that may be removed or no longer used.
9. What is the difference between function declarations and function
expressions?

● Function Declaration: A function defined using the function keyword followed by a


name. It is hoisted, meaning it can be called before its definition in the code.

● Function Expression: A function defined within an expression, often assigned to a


variable. It is not hoisted, meaning it can only be called after its definition.

10. What is a JavaScript Symbol, and when would you use it?

A Symbol is a unique, immutable primitive value in JavaScript, typically used as a key for object
properties. Each Symbol is guaranteed to be unique, even if they have the same description.
They are useful when you want to create private or hidden properties that won’t clash with other
properties, even if they share the same name.

Key Points:

● Uniqueness: Every Symbol is unique.


● Use case: Symbols are often used as keys in objects to avoid property name collisions
and ensure that properties are hidden from methods like Object.keys().

Example Code:
Where would you use Symbols?

● Avoiding Name Clashes: When multiple parts of your codebase may use the same
property names, Symbols ensure there are no collisions.
● Creating Hidden or Private Properties: Since Symbols are not enumerable, they can
be used to store metadata or hidden values in objects that you don't want to expose
accidentally.
● Implementing Protocols: Symbols are useful in libraries where you want to implement
custom behaviors without conflicting with existing object properties (e.g., iterators using
Symbol.iterator).
11. How do the apply, call, and bind methods work in JavaScript? Provide
examples.

● apply(): Calls a function with a given this value and arguments provided as an array.

● call(): Similar to apply(), but takes arguments individually.

● bind(): Creates a new function that, when called, has its this keyword set to the
provided value.

12. What is the purpose of the async iterator, and how does it differ from a
regular iterator?

● An async iterator is used to iterate over data asynchronously, such as when fetching
data from an API. It allows you to work with promises in a for...of loop.
● A regular iterator works synchronously and cannot handle promises.

Example of an Async Iterator:


13. How can you prevent object mutation in JavaScript?

● To prevent object mutation, you can use the following techniques:


○ Use Object.freeze() to make an object immutable.
○ Use spread operators or methods like Object.assign() to create shallow
copies.
○ For deep immutability, you can create utility functions that recursively freeze
objects.

Example with Object.freeze():

14. Print all elements of the nested array arr = [1, [2, [3, 4], 5], 6].
15. Reverse Words in a String In JavaScript.

16. Check for Balanced Parentheses.


17. Remove Duplicates from an Array.
18. Find the Largest Sum of Contiguous Subarray (Kadane’s Algorithm)

19. Find the First Non-Repeated Character in a String.

20. Given an array of n consecutive integers from 1 to n, where one integer


is missing, write a JavaScript function to find the missing number with a
time complexity of O(n).

You might also like