0% found this document useful (0 votes)
11 views

Javascript questions for interview preparation

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)
11 views

Javascript questions for interview preparation

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/ 17

General JavaScript Concepts:

Q 1. What is JavaScript?
Answer: JavaScript is a high-level, interpreted programming language that
enables interactive web pages. It is commonly used for client-side
development but can also be used on the server-side (Node.js).
Q 2. Explain the difference between null and undefined.
Answer: null is a deliberate absence of any object value, while undefined
means that a variable has been declared but has not been assigned a value.
Q 3. What is the purpose of the “typeof” operator?
Answer: The “typeof” operator is used to get the data type of a variable or an
expression, returning a string representation of the data type.
Q 4. Describe the event delegation in JavaScript.
Answer: Event delegation involves using a single event listener to manage all
similar events for multiple elements. This is achieved by leveraging event
bubbling.
Q 5. What is hoisting in JavaScript?
Answer: Hoisting is a JavaScript behaviour where variable and function
declarations are moved to the top of their containing scope during the
compilation phase.
Q 6. Explain the concept of closures.
Answer: Closures are functions that have access to variables from their outer
(enclosing) scope, even after the outer function has finished executing.
Q 7. What is the difference between == and ===?
Answer: == is the equality operator, performing type coercion if necessary,
while === is the strict equality operator, which requires both value and type to
be the same for equality.
Q 8. How does JavaScript handle asynchronous operations?
Answer: JavaScript uses mechanisms like callbacks, promises, and async/await
to handle asynchronous operations, ensuring non-blocking behaviour.
Q 9. Explain the concept of promises.
Answer: Promises are objects representing the eventual completion or failure
of an asynchronous operation. They provide a cleaner way to handle
asynchronous code than callbacks.
Q 10. Describe the differences between let, const, and var.
Answer: let and const were introduced in ES6 for block-scoped variables. let
allows reassignment, while const is for constants. var is function-scoped and is
now considered outdated.
Q 11. What is the event loop in JavaScript?
Answer: The event loop is a mechanism that allows JavaScript to execute code
in a non-blocking way by handling events and asynchronous operations.
Q 12. How does prototypal inheritance work in JavaScript?
Answer: JavaScript uses prototypal inheritance, where objects can inherit
properties and methods from other objects through their prototype chain.

Data Types and Variables:


Q 13. List the primitive data types in JavaScript
Answer: Primitive data types include string, number, Boolean, null, undefined,
and symbol.
Q 14. What is the difference between let, const, and var in terms of scope?
Answer: let and const are block-scoped, while var is function-scoped. Block-
scoped variables are limited to the block (statements inside {}), while function-
scoped variables are limited to the function.
Q 15. How would you check if a variable is an array?
Answer: You can use the Array.isArray() method or the instanceof operator to
check if a variable is an array.
Q 16. Explain the concept of truthy and falsy values in JavaScript.
Answer: Values in JavaScript are truthy if they evaluate to true in a boolean
context and falsy if they evaluate to false. Falsy values include false, 0, null,
undefined, NaN, and '' (empty string).
Q 17. What is the purpose of the typeof operator in JavaScript?
Answer: The typeof operator is used to determine the data type of a value or
expression. It returns a string indicating the data type.
Q 18. How can you convert a string to a number in JavaScript?
Answer: You can use the parseInt() or parseFloat() functions to convert a string
to a number. Additionally, the Number() constructor can be used.

Functions:
Q 19. What is a higher-order function?
Answer: A higher-order function is a function that takes one or more functions
as arguments or returns a function as its result.
Q 20. Explain the difference between function declaration and function
expression.
Answer: Function declarations are hoisted, while function expressions are not.
Function declarations start with the function keyword, while function
expressions can be anonymous or named.
Q 21. What is a callback function?
Answer: A callback function is a function passed as an argument to another
function, to be executed later when a specific event occurs or a condition is
met.
Q 22. What is the purpose of the bind method in JavaScript?
Answer: The bind method is used to create a new function with a specified this
value and, optionally, initial arguments.
Q 23. Describe the concept of function hoisting.
Answer: Function declarations are hoisted to the top of their containing scope
during the compilation phase, allowing them to be used before they are
declared in the code.
Q 24. Explain the differences between function parameters and
arguments.
Answer: Parameters are variables in a function definition, while arguments are
the actual values passed to the function when it is called.
Q 25. What is the purpose of the apply and call methods?
Answer: Both apply and call are used to invoke a function with a specified this
value. The difference is in how arguments are passed; apply takes an array, and
call takes individual arguments.

Objects and Arrays:


Q 26. How do you create an object in JavaScript
Answer: Objects can be created using object literals {}, the Object constructor,
or by using constructor functions with the new keyword.
Q 27. Explain the concept of JSON in JavaScript.
Answer: JSON (JavaScript Object Notation) is a lightweight data interchange
format that is easy for humans to read and write and easy for machines to
parse and generate. It is a subset of JavaScript object notation.
Q 28. What is the difference between null and undefined when accessing
object properties?
Answer: If you try to access a property that doesn't exist, both null and
undefined will be returned. However, if a property is explicitly set to null,
accessing it will return null.
Q 29. How do you loop through the keys and values of an object?
Answer: You can use a for...in loop to iterate over the keys of an object, and
Object.entries() can be used to get an array of key-value pairs for iteration.
Q 30. Explain the concept of array methods in JavaScript (e.g., map, filter,
reduce).
Answer: Array methods like map, filter, and reduce provide functional
programming capabilities for working with arrays. map transforms each
element, filter selects elements based on a condition, and reduce accumulates
values.
Q 31. How do you add/remove elements from an array in JavaScript?
Answer: Elements can be added to the end of an array using push, removed
from the end using pop, added to the beginning using
unshift, and removed from the beginning using shift. The splice method can be
used for more complex operations.
Q 32. What is the purpose of the splice method?
Answer: The splice method is used to change the contents of an array by
removing or replacing existing elements and/or adding new elements in place.

DOM Manipulation:
Q 33. What is the DOM in JavaScript?
Answer: The DOM (Document Object Model) is a programming interface for
web documents. It represents the structure of a document as a tree of objects,
where each object corresponds to a part of the document, such as elements,
attributes, and text.
Q 34. How do you select an element by its ID in JavaScript?
Answer: You can use document.getElementById('id') to select an element by
its ID.
Q 35. Explain the concept of event bubbling.
Answer: Event bubbling is the process where an event starts from the target
element and bubbles up through its ancestors in the DOM tree until it reaches
the root. This allows capturing the event at different levels.
Q 36. How can you create an element dynamically in JavaScript?
Answer: You can use the document.createElement ('elementName') method to
create a new element, and then append it to the DOM using methods like
appendChild or insertBefore.
Q 37. What is the purpose of the querySelector method?
Answer: The querySelector method is used to select the first element that
matches a specified CSS selector. It returns a reference to the first matching
element within the document.
Q 38. How do you handle events in JavaScript?
Answer: Events are handled by attaching event listeners to elements using
methods like addEventListener. The listener is a function that will be executed
when the specified event occurs.
Q 39. Explain the difference between innerHTML and textContent.
Answer: innerHTML is a property that represents the HTML content within an
element, including tags. textContent represents the text content, with HTML
tags treated as text.

ES6 Features:
Q 40. What are template literals in JavaScript?
Answer: Template literals are string literals that allow embedded expressions.
They are enclosed by backticks ( ) and support multi-line strings and
interpolation of variables.
Q 41. Explain the concept of destructuring assignment.
Answer: Destructuring assignment allows you to extract values from arrays or
properties from objects into distinct variables, making it more concise.
Q 42. What is the purpose of the let and const keywords in ES6?
Answer: let and const were introduced in ES6 for block-scoped variables. let
allows reassignment, while const is used for constants.
Q 43. What is arrow function syntax, and how does it differ from regular
function syntax?
Answer: Arrow function syntax is a concise way to write functions in ES6. It has
a shorter syntax and lexically binds the this value, which means it inherits this
from the enclosing scope.
Q 44. Explain the concept of the spread and rest operators.
Answer: The spread operator (...) is used to expand elements of an iterable
(e.g., an array) into individual elements. The rest operator (...) is used in
function parameters to represent an indefinite number of arguments as an
array.
Q 45. What is the purpose of the class keyword in ES6?
Answer: The class keyword in ES6 is used to define classes in JavaScript,
providing a more structured way to create objects and handle inheritance.

Promises and Asynchronous Programming:


Q 46. What is a promise in JavaScript?
Answer: A promise is an object representing the eventual completion or
failure of an asynchronous operation. It has methods like then and catch for
handling success and failure.
Q 47. How do you handle errors in promises?
Answer: Errors in promises can be handled using the catch method or by
chaining a catch callback after the then method.
Q 48. Explain the concept of promise chaining.
Answer: Promise chaining is a technique where multiple promises can be
chained together using the then method, allowing for more concise and
readable asynchronous code.
Q 49. What is the purpose of the async and await keywords?
Answer: The async keyword is used to declare an asynchronous function, and
the await keyword is used inside an async
Function to pause execution until a promise is resolved or rejected.
Q 50. How does the setTimeout function work in JavaScript?
Answer: setTimeout is a function used to schedule the execution of a function
or a code snippet after a specified delay in milliseconds.

Scope and Closures:


Q 51. What is lexical scope in JavaScript?
Answer: Lexical scope is a scope determined by the physical placement of
functions and blocks in the code, allowing inner functions to access variables
from their outer (enclosing) scope.
Q 52. Explain the difference between global scope and local scope.
Answer: Global scope refers to the context in which variables are accessible
throughout the entire program, while local scope refers to the context in which
variables are accessible only within a specific function or block.
Q 53. How does closure work in JavaScript?
Answer: Closures allow functions to retain access to variables from their outer
(enclosing) scope even after the outer function has finished executing.
Q 54. What is the purpose of the IIFE (Immediately Invoked Function
Expression) pattern?
Answer: An IIFE is a function that is immediately executed after being defined.
It is often used to create a private scope and avoid polluting the global scope.

Testing and Debugging:


Q 55. What is unit testing, and how can it be done in JavaScript?
Answer: Unit testing involves testing individual units or components of a
program in isolation. JavaScript unit testing frameworks like Jest, Mocha, and
Jasmine are commonly used for this purpose.
Q 56. Explain the concept of debugging in JavaScript.
Answer: Debugging is the process of identifying and fixing errors in code.
Developers use tools like browser developer tools or integrated development
environments (IDEs) to set breakpoints, inspect variables, and step through
code.
Q 57. What is the purpose of the console.log method?
Answer: console.log is a method used for logging messages to the console
during development. It is a helpful tool for debugging and understanding the
flow of a program.

Security:
Q 58. How do you prevent cross-site scripting (XSS) attacks in JavaScript?
Answer: To prevent XSS attacks, you should:
Input Validation: Validate and sanitize user input on the server side.
Output Encoding: Encode user-generated content before displaying it. Use functions
like encodeURIComponent or frameworks that automatically escape data.
Q 59. Explain the concept of Content Security Policy (CSP).
Answer: Content Security Policy (CSP) is a security standard that helps prevent XSS
attacks. It allows you to define a set of rules for the browser about which resources
can be loaded and executed. This includes specifying trusted sources for scripts,
styles, images, and other resources, reducing the risk of unauthorized script
execution.

Web Development:
Q 60. What is the purpose of the localStorage and sessionStorage objects?
Answer: localStorage and sessionStorage are web storage options in the browser.
localStorage: Persists data with no expiration date. The data remains even when the
browser is closed and reopened.
sessionStorage: Persists data only for the duration of the page session. The data is lost
when the browser tab or window is closed.
Q 61. How can you make an AJAX request in JavaScript?
Answer: You can make an AJAX (Asynchronous JavaScript and XML) request using the
XMLHttpRequest object or, more commonly, using the fetch API.
Q 62. Explain the concept of Single Page Applications (SPAs).
Answer: Single Page Applications (SPAs) are web applications that load a single HTML
page and dynamically update the content as the user interacts with the app. SPAs use
AJAX to retrieve and load data without requiring a full page reload. Frameworks like
React, Angular, and Vue.js are commonly used to build SPAs.
Q 63. What is the purpose of the fetch API in JavaScript?
Answer: The fetch API is used to make network requests (such as fetching data from a
server) similar to XMLHttpRequest. It is more modern and provides a cleaner syntax.
fetch returns a Promise that resolves to the Response to that request, allowing you to
handle the response asynchronously.

Frameworks and Libraries:


Q 64. What is the difference between Angular, React, and Vue.js?
Angular: A complete MVC framework by Google. It uses TypeScript, has a steep
learning curve, and provides a comprehensive set of tools for building large-scale
applications.
React: A JavaScript library for building user interfaces, developed by Facebook. React
uses a virtual DOM for efficient updates and focuses on component-based
architecture.
Vue.js: A progressive JavaScript framework that is incrementally adoptable. Vue.js is
designed from the ground up to be incrementally adaptable and is easy to integrate
with other libraries or existing projects.
Q 65. Explain the concept of virtual DOM in React.
Answer: The virtual DOM is a programming concept where a virtual representation of
the user interface is kept in memory and synced with the real DOM by a library such
as React. This allows React to update only the changed parts of the DOM, reducing
the amount of manipulation needed and improving performance.
Q 66. What is state management in React?
Answer: State management in React involves managing the state (data) of a
component. React components can have local state, but for larger applications, a
state management solution like Redux or the Context API may be used to manage
global state and simplify data flow.
Q 67. What is the purpose of the useEffect hook in React?
Answer: The useEffect hook in React is used to perform side effects in functional
components. It allows you to execute code after the component renders, handle
subscriptions, or perform cleanup. It replaces lifecycle methods like
componentDidMount, componentDidUpdate, and componentWillUnmount in class
components.
Q 68. How do you create a component in Angular?
Answer: In Angular, a component is created by defining a TypeScript class with the
@Component decorator. This class typically includes metadata such as the
component's selector, template, and styles.

Miscellaneous:
Q 69. What is the difference between window.onload and the DOMContentLoaded
event?
window.onload: This event is fired when all assets on the page, including images and
scripts, have fully loaded.
DOMContentLoaded: This event is fired when the HTML document has been
completely loaded and parsed, without waiting for stylesheets, images, and
subframes to finish loading.
Q 70. Explain the concept of the same-origin policy.
Answer: The same-origin policy is a security measure in web browsers that restricts
web pages from making requests to a different domain than the one that served the
web page. This policy helps prevent malicious websites from making unauthorized
requests on behalf of the user.
Q 71. What is the purpose of the async attribute in script tags?
Answer: The async attribute in script tags is used to indicate that the script should be
executed asynchronously. It allows the HTML parsing and rendering to continue while
the script is being fetched, reducing the page load time.
Q 72. How do you create a cookie in JavaScript?
You can create a cookie using the document.cookie property. For example:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
This sets a cookie named "username" with the value "John Doe," an expiration date,
and a path.
Q 73. Explain the concept of AJAX.
Answer: AJAX (Asynchronous JavaScript and XML) is a technique used in web
development to send and receive data asynchronously between a web browser and a
server. It allows updating parts of a web page without requiring a full page reload,
providing a smoother and more dynamic user experience.

Advanced JavaScript:
Q 74. What is the purpose of the Object.create method?
Answer: The Object.create method is used to create a new object with the specified
prototype object and properties. It allows for prototypal inheritance without the need
for a constructor function.
Q 75. Describe the concept of memoization in JavaScript.
Answer: Memoization is an optimization technique where the results of expensive
function calls are cached, so if the same inputs occur again, the function can return
the cached result instead of recalculating it.
Q 76. What is the purpose of the Symbol data type?
Answer: The Symbol data type in JavaScript is used to create unique identifiers. Unlike
other data types, symbols are unique, ensuring that they are distinct from each other.
This makes them useful for creating property keys in objects, avoiding naming
conflicts.
Q 77. Explain the concept of generators in JavaScript.
Answer: Generators are special types of functions in JavaScript that can be paused
and resumed, allowing for the generation of a sequence of values on demand. They
are defined using the ‘function*’ syntax and use the yield keyword to produce a value.
Q 78. How do you handle asynchronous code in Node.js?
Answer: In Node.js, asynchronous code is commonly handled using callbacks,
promises, or the async/await syntax. Common patterns include using the fs module
for file operations, and the http or https module for making HTTP requests.

Interview Problem-Solving:
Q 79. Write a function to reverse a string in JavaScript.

function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString('hello'));
// Outputs: 'olleh'

Q 80. Implement a function to find the factorial of a number.


function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
Q 81. Create a function to check if a given string is a palindrome.
function isPalindrome(str) {
const reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}
console.log(isPalindrome('radar')); // Outputs: true }
}
Q 82. Implement a function to find the maximum element in an array.
function findMax(arr) { // Outputs: 120
console.log(factorial(5));
return Math.max(...arr);
}

console.log(findMax([1, 5, 3, 9, 2])); // Outputs: 9

Q 83. Write a function to remove duplicate elements from an array.

function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));
// Outputs: [1, 2, 3, 4, 5]

Q 84. Create a function to find the sum of all numbers in an array.

function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
console.log(sumArray([1, 2, 3, 4, 5]));
// Outputs: 15
Q 85. Implement a function to check if a number is prime.
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
console.log(isPrime(7));
// Outputs: true

Algorithmic Thinking:
Q 86. Explain the difference between breadth-first search (BFS) and depth-first
search (DFS).
Answer: Breadth-First Search (BFS): Visits all the neighbors of a node before moving
on to the next level of nodes. It uses a queue data structure.
Depth-First Search (DFS): Explores as far as possible along one branch before
backtracking. It uses a stack or recursion.
Q 87. Write a function to determine if two strings are anagrams.

function areAnagrams(str1, str2) {


return str1.split('').sort().join('') === str2.split('').sort().join('');
}
console.log(areAnagrams('listen', 'silent'));
// Outputs: true

Q 88. Explain the concept of Big O notation.


Answer: Big O notation is a mathematical notation used to describe the performance
or complexity of an algorithm. It characterizes the worst-case scenario in terms of
time or space complexity. Common notations include O(1) for constant time, O(n) for
linear time, O(log n) for logarithmic time, etc.
Debugging and Troubleshooting:
Q 89. How do you use the browser developer tools for debugging?
Answer: Open the browser's developer tools (usually by pressing F12 or right-clicking
and selecting "Inspect").
Go to the "Sources" tab.
Set breakpoints by clicking on the line number.
Use the "Console" tab for logging and interacting with variables.
Q 90. What is the purpose of breakpoints in debugging?
Answer: Breakpoints are markers set in the code that pause the execution of the
program at a specific point. They allow developers to inspect the program's state, step
through code line by line, and identify issues.
Q 91. Explain common JavaScript errors and how to fix them.
Answer: ReferenceError: Variable or function is not defined.
Fix: Ensure the variable or function is declared and in scope.
TypeError: An operation is not supported or variable is not of the expected type.
Fix: Check variable types and ensure correct method usage.
SyntaxError: Code is not written according to the language syntax.
Fix: Correct syntax errors.

ES2020 and Beyond:


Q 92. What are the features introduced in ECMAScript 2020?
Answer: ECMAScript 2020 introduced features like globalThis, BigInt, dynamic
import(), optional chaining (?.), and nullish coalescing (??) operators.
Q 93. Explain the purpose of the BigInt data type.
Answer: The BigInt data type in JavaScript is used to represent arbitrary-precision
integers. It allows working with integers beyond the limits of the Number data type.
Q 94. What is the Optional Chaining operator in JavaScript?
Answer: The Optional Chaining operator (?.) is used to access properties of an object
without the need to explicitly check if each level of the property hierarchy exists. If
property is undefined or null, the expression returns undefined instead of throwing
an error.

Bonus Questions:
Q 95. What is WebAssembly, and how does it relate to JavaScript?
Answer: WebAssembly (Wasm) is a binary instruction format designed for high-
performance execution on web browsers. It allows running code written in languages
like C, C++, and Rust on the web. While WebAssembly and JavaScript can work
together, they serve different purposes, with WebAssembly focusing on performance-
intensive tasks.
Q 96. Explain the concept of progressive web apps (PWAs).
Answer: Progressive Web Apps are web applications that provide a native app-like
experience on the web. They use modern web capabilities to deliver features such as
offline functionality, push notifications, and responsiveness. PWAs are designed to
work on any platform and device.
Q 97. What are the benefits of using a bundler like Webpack in a JavaScript project?
Answer: Webpack is a module bundler that helps manage and bundle project
dependencies. The benefits include efficient code organization, dependency
management, code splitting for better performance, and the ability to use various
assets like stylesheets and images in a modular way.
Q 98. How does JavaScript differ from other programming languages like Java or
Python?
Execution Environment: JavaScript is mainly used as a scripting language in web
browsers, while Java and Python are often used for server-side development and
other applications.
Typing: JavaScript is dynamically typed, while Java is statically typed, and Python is
dynamically typed.
Syntax: Each language has its syntax and programming paradigms (e.g., Java is object-
oriented, Python supports multiple paradigms, etc.).
Q 99. Explain the concept of CORS (Cross-Origin Resource Sharing) in the context of
web development.
Answer: Cross-Origin Resource Sharing (CORS) is a security feature implemented by
web browsers to control how web pages in one domain can request and interact with
resources hosted on another domain. Due to the Same-Origin Policy, web browsers
restrict cross-origin requests initiated by JavaScript. CORS is a mechanism that
enables servers to specify which origins are permitted to access their resources. It
involves the use of HTTP headers, such as Access-Control-Allow-Origin, to define the
allowed origins for cross-origin requests.
Q 100. What is the event loop in JavaScript, and how does it contribute to
asynchronous programming?
Answer: The event loop is a crucial part of JavaScript's concurrency model that allows
the execution of non-blocking, asynchronous code. In a single-threaded environment,
the event loop manages the execution of code by continuously checking the message
queue for tasks. When a task is completed or an event occurs, it is added to the
message queue. The event loop then picks tasks from the queue and executes them
one by one.
In asynchronous programming, functions like callbacks, promises, and async/await
leverage the event loop to handle operations such as I/O, making it possible to
perform tasks without blocking the main execution thread. This ensures a responsive
and efficient user experience in web applications.

For more valuable insights and resources, feel free to


connect with Bhawani.
@bhawanirathore7773

You might also like