JavaScript
Important Note for Students:
This list of questions and answers is like a helpful guide for your upcoming interview. It's designed to
give you an idea of what to expect and help you get ready.
But remember:
1. Variety of Questions: The same questions can be asked in many different ways, so don't just
memorise the answers. Try to understand the concept behind each one.
2. Expect Surprises: There might be questions during your interview that are not on this list. It's
always good to be prepared for a few surprises.
3. Use This as a Starting Point: Think of this material as a starting point. It shows the kind of
questions you might encounter, but it's always good to study beyond this list during your course.
1. What is JavaScript?
JavaScript is a versatile programming language primarily used for adding interactivity, dynamic
behavior, and enhanced user experiences to websites and web applications. It is executed by
web browsers and allows developers to manipulate the Document Object Model (DOM), handle
events, and communicate with servers using APIs.
2. How can you check if a variable is an array?
You can use the [Link]() method to determine whether a variable is an array or not.
3. What is the purpose of the [Link]() method?
The [Link]() method is used to prevent the default behavior of an event in the
browser, such as preventing a form from submitting or a link from navigating.
4. What is the ternary operator in JavaScript?
The ternary operator (condition ? expr1 : expr2) is a shorthand for an if-else statement. It returns
expr1 if the condition is true, and expr2 otherwise.
5. What is the difference between the spread operator (...) and the rest parameter?
The spread operator is used to split an array or object into individual elements, while the rest
parameter is used in function parameters to collect multiple arguments into a single array.
6. What is the NaN value in JavaScript?
NaN stands for "Not-a-Number" and is a special value representing an unrepresentable or
undefined numeric value. It's often the result of invalid mathematical operations.
[Link] Shaping “skills” for “scaling” higher…!!! Page 1 of 9
7. What is the purpose of the localStorage object?
The localStorage object provides a way to store key-value pairs in a web browser, persisting
even after the browser is closed. The data stored in localStorage is accessible across different
pages on the same domain.
8. How can you convert a string to an integer in JavaScript?
You can use functions like parseInt() or Number() to convert a string to an integer.
9. What is event delegation and why is it useful?
Event delegation is a technique where you attach a single event listener to a common ancestor
of multiple elements, instead of attaching listeners to each individual element. This optimizes
performance and simplifies handling events for dynamically generated elements.
10. How do you clone an array in JavaScript?
You can use the slice() method, the spread operator ([...array]), or methods like concat() or
[Link]() to clone an array in JavaScript.
11. What is a callback function?
A callback function is a function passed as an argument to another function and is executed
later, usually after an asynchronous operation or an event occurs.
12. What is the purpose of the bind() method?
The bind() method is used to create a new function with a specific context (value of this) and,
optionally, pre-set arguments. It's often used to ensure that a function is called with a specific
context, regardless of how it's invoked.
13. What is the difference between let, const, and var for variable declaration?
let and const were introduced in ES6 and have block scope, while var has function scope. const
declares a constant variable that cannot be reassigned, while let and var allow reassignment.
14. How do you iterate through an array in JavaScript?
You can use a variety of methods, including for loops, forEach(), for...of loops, and methods like
map(), filter(), and reduce().
15. What is the purpose of the [Link]() method?
The [Link]() method converts a JavaScript object or value into a JSON string
representation, making it suitable for data exchange or storage.
16. What does the typeof operator do?
The typeof operator returns a string indicating the data type of a given value. It's commonly
used to differentiate between basic data types like "string," "number," "object," "function," etc.
[Link] Shaping “skill” for “scaling” higher…!!! Page 2 of 9
17. What is the difference between synchronous and asynchronous code?
Synchronous code executes in sequence, blocking further execution until it completes.
Asynchronous code allows other operations to continue while the asynchronous task is being
performed, often achieved using callbacks, promises, or async/await.
18. What is a JavaScript event?
A JavaScript event is an action that occurs in the browser, such as a button click, mouse
movement, or keyboard press. Event listeners are used to execute code in response to these
events.
19. What is object destructuring in JavaScript?
Object destructuring is a way to extract properties from an object and assign them to variables.
It simplifies code by providing a concise syntax to access and use object properties.
20. What is the purpose of the super keyword in class inheritance?
In class inheritance, the super keyword is used to call methods from a parent class. It's
commonly used in the constructor to call the parent class's constructor and access its properties
and methods.
22. How does JavaScript differ from Java?
Despite the similar names, JavaScript and Java are distinct languages. JavaScript is a
lightweight scripting language used for web development, while Java is a full-fledged
programming language known for its versatility across various applications, including desktop
and mobile development.
23. What is the DOM?
The Document Object Model (DOM) is a programming interface provided by web browsers. It
represents the structure of a web page as a hierarchical tree of objects. Developers can use
JavaScript to manipulate these objects, changing content, styles, and behavior dynamically
without requiring a page refresh.
24. What are closures in JavaScript?
Closures are a feature in JavaScript that allow functions to maintain access to their lexical
scope even after the function has finished executing. This enables the creation of private
variables, data encapsulation, and the implementation of various design patterns like the
Module Pattern.
25. Explain the concept of asynchronous programming in JavaScript.
Asynchronous programming in JavaScript involves executing tasks concurrently without
blocking the main execution thread. This is crucial for handling tasks like fetching data from
servers or performing time-consuming operations without freezing the user interface. JavaScript
achieves this through mechanisms like callbacks, promises, and async/await.
[Link] Shaping “skill” for “scaling” higher…!!! Page 3 of 9
26. What is the purpose of the "this" keyword in JavaScript?
The "this" keyword refers to the current context or object. Its value can change depending on
how a function is called. In a method, "this" generally refers to the object the method is called
on. However, in regular functions, "this" can vary based on how the function is invoked, such as
globally or as a callback.
27. What are promises in JavaScript?
Promises are a way to handle asynchronous operations in a more structured and readable
manner. They represent a value that may be available now or in the future, and they provide
methods to handle success and failure cases. Promises help avoid the "callback hell" problem
and simplify error handling.
28. What is the difference between "null" and "undefined" in JavaScript?
"undefined" in JavaScript signifies the absence of a value or the value of an uninitialized
variable, while "null" is an explicit value representing the absence of any object value. In
essence, "undefined" indicates the lack of definition, whereas "null" represents the intentional
absence of a value.
29. How can you avoid or handle potential issues with asynchronous code, such as
callback hell or race conditions?
To avoid callback hell, you can use promises or the async/await syntax for more structured and
readable asynchronous code. To address race conditions, you can use techniques like using
locks or mutexes, utilizing synchronization methods, or employing the concept of "promises" to
ensure proper execution order.
30. Explain the concept of event delegation in JavaScript.
Event delegation is a design pattern where you attach a single event listener to a higher-level
container element, instead of attaching multiple listeners to individual child elements. This is
particularly useful when dealing with dynamically generated content, as it optimizes memory
usage and reduces the overhead of managing many event listeners.
Remember, while these questions cover a range of JavaScript topics, it's important to have a
comprehensive understanding of the language, its features, and its ecosystem to perform well in
interviews.
31. What are the different data types in JavaScript?
JavaScript has several data types, including primitive types: number, string, boolean, null,
undefined, and symbol (introduced in ES6), and reference types: object, which includes arrays,
functions, and objects created with constructors.
[Link] Shaping “skill” for “scaling” higher…!!! Page 4 of 9
32. What is hoisting in JavaScript?
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top
of their containing scope during compilation. However, only declarations are hoisted, not
assignments. This means you can use variables and functions before they are declared, but it's
recommended to declare them first for code clarity.
33. How does prototypal inheritance work in JavaScript?
JavaScript uses prototypal inheritance, where objects can inherit properties and methods from
other objects (their prototypes). Each object has a prototype object from which it inherits. If a
property or method is not found in the object itself, JavaScript looks up the prototype chain to
find it in its prototype or further up the chain.
34. What is the "this" keyword in JavaScript functions?
In JavaScript, the value of the "this" keyword depends on how a function is invoked. In a regular
function, "this" refers to the global object (window in browsers), while in a method, "this" refers
to the object the method is called on. You can also change the value of "this" using functions
like call(), apply(), and bind().
35. How do you handle errors in JavaScript?
Errors in JavaScript can be handled using try...catch blocks. The "try" block contains the code
that might cause an error, and if an error occurs, it's caught by the "catch" block, allowing you to
handle the error gracefully. Additionally, you can use the "finally" block to execute code
regardless of whether an error occurred or not.
36. What are arrow functions in JavaScript?
Arrow functions are a concise syntax introduced in ES6 for writing functions. They have a
shorter syntax and do not bind their own "this" value; instead, they inherit the "this" value from
the surrounding code. Arrow functions are particularly useful for short, single-expression
functions and for avoiding issues related to "this" binding.
37. What is the event loop in JavaScript and how does it work?
The event loop is a fundamental part of JavaScript's concurrency model. It manages the
execution of asynchronous code, ensuring that synchronous code runs to completion before
processing any pending asynchronous tasks. The event loop constantly checks the call stack
and task queue, moving tasks from the queue to the stack when the stack is empty.
38. What are modules in JavaScript and how do you achieve modularity?
Modules are a way to organize code into reusable and maintainable units. Prior to ES6,
JavaScript lacked built-in module support. However, you could achieve modularity using the
revealing module pattern or other patterns. With ES6, native support for modules was
introduced, allowing you to use the import and export statements to control scope and sharing
of code.
[Link] Shaping “skill” for “scaling” higher…!!! Page 5 of 9
39. How can you improve the performance of your JavaScript code?
There are several ways to enhance JavaScript performance, including:
• Minifying and compressing code to reduce file size.
• Avoiding excessive DOM manipulation for better rendering performance.
• Using event delegation to minimize the number of event listeners.
• Implementing efficient algorithms and data structures.
• Caching and reusing frequently accessed values.
• Using asynchronous code to prevent blocking the main thread.
• Question: Explain the concept of promises and async/await for handling asynchronous
code.
Promises are objects that represent the eventual completion or failure of an asynchronous
operation. They simplify the handling of asynchronous code and make it more readable.
Async/await is a more recent addition, introduced in ES8, that provides a more synchronous-like
syntax for working with promises. The async keyword is used to define an asynchronous
function, and the await keyword is used to pause execution until a promise is resolved.
Remember, while preparing for interviews, it's important to not just memorize answers, but to
thoroughly understand the underlying concepts and practice implementing them. This will help
you provide thoughtful and accurate responses during your interview.
40. What is the difference between null and undefined?
Both null and undefined represent the absence of a value, but they are used in slightly different
contexts. undefined is typically assigned by the system to variables that have been declared but
not initialized. null is often used as an intentional absence of value, indicating that a variable has
no value or an object property has no reference.
41. How do you handle synchronous and asynchronous operations in JavaScript?
Synchronous operations block the execution until they complete, while asynchronous operations
allow the program to continue executing while waiting for the operation to finish. In JavaScript,
asynchronous operations are managed using callbacks, promises, and async/await. Callbacks
were traditionally used, but promises and async/await provide more structured and readable
ways to handle asynchronous code.
42. What is the difference between == and === operators?
The == operator is the equality operator, and it checks whether two values are equal after
performing type coercion. The === operator is the strict equality operator, and it checks whether
two values are equal without performing type coercion. Using === is generally recommended
because it avoids unexpected type conversions.
[Link] Shaping “skill” for “scaling” higher…!!! Page 6 of 9
43. What is event bubbling in JavaScript?
Event bubbling is a mechanism where an event starts at the target element that triggered it and
then bubbles up through its parent elements in the DOM hierarchy. This means that if an event
occurs on a nested element, it will trigger event handlers on its parent elements as well, in the
order they are nested.
44. How do you clone an object in JavaScript?
There are a few ways to clone objects in JavaScript. One common method is to use the
[Link]() method or the spread syntax (...) to create a shallow copy of the object. For
more complex objects or deep cloning, you might need to use libraries like lodash or manually
implement recursive cloning.
45. What is the purpose of the localStorage and sessionStorage objects?
Both localStorage and sessionStorage are web storage APIs in browsers that allow you to store
key-value pairs locally on the client side. The main difference is that data stored in localStorage
persists even after the browser is closed, while data in sessionStorage is only available for the
duration of a browser session.
46. How can you prevent cross-site scripting (XSS) attacks in JavaScript?
Cross-site scripting attacks occur when user-provided input is not properly sanitized and
executed as code in a web page. To prevent XSS attacks, you should:
• Always sanitize and validate user inputs before displaying them on a page.
• Use content security policies (CSP) to restrict what resources can be loaded and
executed.
• Avoid using eval() and similar functions that can execute dynamic code.
• Use encoding functions like encodeURIComponent() or libraries like DOMPurify to
sanitize user input.
47. What are the benefits and drawbacks of using a framework like React or Angular?
Frameworks like React and Angular offer benefits such as structured architecture, component
reusability, and efficient updates through virtual DOM. They also provide tools for state
management and routing. However, using a framework can introduce a learning curve, and the
initial setup might be more complex compared to vanilla JavaScript. It's essential to choose a
framework that aligns with the project's requirements and team expertise.
48. Explain the concept of closures and provide an example.
A closure is a function that "remembers" the variables from its containing lexical scope even
after that scope has finished executing. This allows the function to access and manipulate those
variables later, even if they are not in scope anymore. Here's a simple example:
[Link] Shaping “skill” for “scaling” higher…!!! Page 7 of 9
function createCounter() {
let count = 0;
return function() {
return ++count;
};
}
const counter = createCounter();
[Link](counter()); // Outputs: 1
[Link](counter()); // Outputs: 2
In this example, the inner function maintains access to the count variable even though the
createCounter() function has finished executing. Each time the inner function is called, it
increments and returns the count. This demonstrates the concept of closures in JavaScript.
Remember, while studying these questions and answers is beneficial, understanding the
underlying concepts and practicing with real code examples will greatly enhance your
performance in interviews.
49. What is a closure in JavaScript?
A closure is a function that retains access to its outer function's variables even after the outer
function has completed execution.
50. What will be the output of the following code?
[Link](5 + "3");
Output: "53"
Explanation: The plus operator is used for both addition and string concatenation in JavaScript.
In this case, since one operand is a string ("3"), JavaScript converts the number (5) into a string
and concatenates them, resulting in "53".
51. What will be the output of the following code?
[Link](2 * "3");
Output: 6
Explanation: The multiplication operator (*) is a numeric operator in JavaScript. When one
operand is a string ("3"), JavaScript automatically converts it to a number before performing the
multiplication operation.
52. What will be the output of the following code?
[Link](typeof NaN);
Output: "number"
[Link] Shaping “skill” for “scaling” higher…!!! Page 8 of 9
Explanation: NaN (Not-a-Number) is a special value in JavaScript that represents an invalid
number. The typeof operator returns the type of the value, and in this case, NaN is considered a
number.
53. What will be the output of the following code?
[Link]([] == []);
Output: false
Explanation: When comparing arrays using the equality operator (==), JavaScript checks for
reference equality, not the equality of individual elements. In this case, two separate array
instances are compared, so the result is false.
54. What will be the output of the following code?
[Link](1 + true);
Output: 2
Explanation: In JavaScript, true is internally represented as 1 and false as 0 when used in a
numeric context. Therefore, 1 (the numeric value of true) is added to 1, resulting in 2.
These questions cover a range of JavaScript concepts related to type conversion, operator
behavior, and array comparison. Feel free to ask more questions if you have any specific
scenarios in mind!
[Link] Shaping “skill” for “scaling” higher…!!! Page 9 of 9