Interview QNA
Interview QNA
Store.CodeWithCurious.com
For More Coding Books & Handwritten Notes © 2024 All Rights Reserved CodeWithCurious
100 Most Asked
Python Interview QnA
Made By:
1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity and
readability. It emphasizes code readability and encourages a clean and concise coding style.
2. What are the key features of Python?
Key features of Python include its easy-to-read syntax, dynamic typing, automatic memory
management, extensive standard library, and support for multiple programming paradigms.
3. How is Python different from other programming languages?
Python stands out with its simplicity, readability, and easy-to-understand syntax. It has a
large and active community, extensive libraries, and is widely used in various domains such
as web development, data analysis, and scientific computing.
4. What is PEP 8?
PEP 8 is the official style guide for Python code. It provides guidelines on how to format
Python code to enhance readability and maintain consistency across projects.
5. What are Python modules?
Python modules are files containing Python code that define functions, classes, and
variables. They allow code reuse and organization, making it easier to manage and maintain
larger projects.
6. What is a Python package?
A Python package is a way to organize related modules into a directory hierarchy. It allows
for a logical grouping of modules, making it easier to manage and distribute code.
7. How do you comment in Python?
Comments in Python are denoted by the # character. Anything after the # is considered a
comment and is ignored by the Python interpreter.
8. What are Python data types?
Python supports various data types, including integers, floating-point numbers, strings,
lists, tuples, dictionaries, and booleans. Each data type has its own characteristics and uses.
9. What is type conversion in Python?
Type conversion, also known as type casting, is the process of converting one data type into
another. Python provides built-in functions like int(), float(), str(), etc., to perform type
conversion.
10. What is string interpolation in Python?
String interpolation in Python allows you to embed expressions or variables within a string,
making it easier to construct dynamic strings. It can be done using f-strings or the format()
method.
11. What are Python conditional statements?
Python conditional statements, such as if, elif, and else, allow you to perform different
actions based on certain conditions. They control the flow of the program based on the
truthfulness of the conditions.
12. What are Python loops?
Python loops, like for and while, enable you to execute a block of code repeatedly. They
iterate over a sequence or execute until a specific condition is met.
13. What is the difference between range() and xrange() in Python 2?
In Python 2, range() generates a list of numbers, while xrange() returns an iterator. xrange() is
more memory-efficient for large ranges because it generates values on the fly.
14. What are Python functions?
Python functions are reusable blocks of code that perform a specific task. They help in code
organization, reusability, and modularity. Functions can accept arguments and return values.
15. What is the difference between a function and a method in Python?
In Python, a function is a standalone block of code that can be called independently. A
method, on the other hand, is a function that is associated with an object or a class and can
access the object's data.
16. How do you define a function in Python?
A function in Python is defined using the def keyword, followed by the function name,
parentheses for parameters (if any), and a colon. The function body is indented below.
17. What is the __init__ method used for?
The __init__ method is a special method in Python classes that is automatically called when
an object is created from the class. It is used to initialize the object's attributes and perform
setup tasks.
18. What is object-oriented programming (OOP)?
Object-oriented programming (OOP) is a programming paradigm that organizes code into
objects, which are instances of classes. It emphasizes encapsulation, inheritance, and
polymorphism.
19. What are Python classes and objects?
In Python, a class is a blueprint that defines the properties and behaviors of objects. An
object is an instance of a class. It represents a specific entity and can interact with other
objects.
20. How do you create an object in Python?
An object is created by calling the class as if it were a function. The class acts as a
constructor, initializing the object and returning it.
21. What is inheritance in Python?
Inheritance is a mechanism in Python that allows a class to inherit properties and methods
from another class. It enables code reuse and supports the creation of hierarchical class
structures.
22. What is method overriding?
Method overriding is the process of defining a method in a subclass that has the same name
as a method in its superclass. The subclass method overrides the implementation of the
superclass method.
23. What is method overloading?
Method overloading is not directly supported in Python. However, you can achieve similar
functionality by defining a single method with default argument values or using variable-
length arguments.
24. What is encapsulation in Python?
Encapsulation is the process of bundling data and methods together within a class. It allows
for data hiding and controlling access to the object's attributes using getter and setter
methods.
25. What is polymorphism in Python?
Polymorphism is the ability of an object to take on multiple forms or have multiple
behaviors. In Python, polymorphism is achieved through method overriding and method
overloading (using default argument values or variable-length arguments).
26. What is a generator in Python?
A generator in Python is a function that returns an iterator. It allows you to generate a
sequence of values on-the-fly, conserving memory and improving performance.
27. What are decorators in Python?
Decorators are a way to modify the behavior of a function or class without directly changing
its source code. They are defined using the @decorator_name syntax and can be used for
tasks like logging, timing, or modifying function arguments.
28. What is a lambda function in Python?
A lambda function is an anonymous function in Python that is defined using the lambda
keyword. It is a shorthand way to create small, one-line functions without explicitly defining
a function using def.
29. What is a module in Python?
A module in Python is a file containing Python definitions and statements. It can be
imported and used in other Python programs to access its functions, classes, and variables.
30. How do you import modules in Python?
Modules can be imported in Python using the import keyword followed by the module name.
You can also import specific objects from a module using the from module_name import
object_name syntax.
31. What is a virtual environment in Python?
A virtual environment in Python is a self-contained directory that contains a specific version
of Python interpreter and installed packages. It allows you to isolate Python environments
for different projects and manage their dependencies.
32. What are exceptions in Python?
Exceptions in Python are events that occur during the execution of a program that disrupt
the normal flow of the code. They can be handled using try-except blocks to gracefully
handle errors and exceptions.
33. What is error handling in Python?
Error handling in Python involves using try-except blocks to catch and handle exceptions
that may occur during the execution of the code. It allows for graceful recovery from errors
and prevents the program from crashing.
34. What is the purpose of the try-except-else-finally block in Python?
The try-except-else-finally block in Python is used for exception handling. The try block
contains the code that may raise an exception. The except block is used to handle specific
exceptions. The else block is executed if no exceptions occur. The finally block is always
executed, regardless of whether an exception occurred or not.
35. What are the built-in data structures in Python?
Python provides several built-in data structures, including lists, tuples, dictionaries, sets,
and strings. These data structures offer different ways to store, manipulate, and retrieve
data.
36. What is a list in Python?
A list in Python is an ordered collection of items that can be of different data types. It is
mutable, meaning its elements can be modified. Lists are denoted by square brackets [ ] and
can contain elements separated by commas.
37. What is a tuple in Python?
A tuple in Python is an ordered collection of items similar to a list. However, tuples are
immutable, meaning their elements cannot be changed once assigned. Tuples are denoted
by parentheses ( ) and can contain elements separated by commas.
38. What is a dictionary in Python?
A dictionary in Python is an unordered collection of key-value pairs. It is mutable and allows
fast access to values based on their associated keys. Dictionaries are denoted by curly
braces { } and use colons : to separate keys and values.
39. What is a set in Python?
A set in Python is an unordered collection of unique elements. It is mutable and provides
mathematical set operations like union, intersection, and difference. Sets are denoted by
curly braces { } or the set() function.
40. What is a string in Python?
A string in Python is a sequence of characters enclosed in single quotes, double quotes, or
triple quotes. It is immutable, meaning its individual characters cannot be changed. Strings
can be manipulated and operated upon in various ways.
41. How do you concatenate strings in Python?
Strings can be concatenated in Python using the + operator or by using the .join() method.
The + operator concatenates two strings, while the .join() method concatenates multiple
strings using a specified delimiter.
42. How do you format strings in Python?
Strings can be formatted in Python using the % operator, the str.format() method, or f-
strings (formatted string literals). These methods allow you to insert values into
placeholders within a string.
43. What are file handling operations in Python?
File handling operations in Python involve reading from and writing to files. Python provides
built-in functions and methods to open, read, write, and close files.
44. How do you open and close a file in Python?
Files can be opened in Python using the open() function, which takes the file name and the
mode of operation as arguments. The close() method is used to close an opened file and free
up system resources.
45. What are the different file modes in Python?
The different file modes in Python include "r" for reading, "w" for writing (overwriting
existing content), "a" for appending, "x" for exclusive creation (fails if the file already exists),
and "b" for binary mode.
46. What is exception handling in file operations?
Exception handling in file operations involves handling potential errors that may occur while
performing file-related operations. This ensures that the program handles file-related
exceptions gracefully and avoids crashes or data loss.
47. What is a context manager in Python?
A context manager in Python is an object that defines the methods __enter__() and
__exit__() to enable the with statement. It allows for resource allocation and deallocation,
such as automatically closing a file after use.
48. What is a generator function in Python?
A generator function in Python is a special type of function that uses the yield keyword
instead of return. It allows you to generate a sequence of values on-the-fly without storing
them all in memory at once.
49. What is a list comprehension in Python?
A list comprehension in Python is a concise way to create lists based on existing lists or
other iterable objects. It allows you to combine looping and conditional logic in a single line
of code.
50. What is the pass statement in Python?
The pass statement in Python is a placeholder statement that does nothing. It is used as a
syntactic placeholder when a statement is required by the Python syntax, but no action is
needed.
51. What is the purpose of the self parameter in Python?
The self parameter is used as a reference to the current instance of a class in Python. It
allows accessing the attributes and methods of that instance within the class definition.
52. What is the difference between a shallow copy and a deep copy in Python?
In Python, a shallow copy creates a new object that references the original data, while a
deep copy creates a new object with completely independent copies of the original data.
Modifying the original data does not affect the deep copy, but it can affect the shallow copy.
53. What are the advantages of using Python for web development?
Python offers several advantages for web development, including a wide range of
frameworks (such as Django and Flask), a large community, extensive libraries, and easy
integration with other technologies.
54. What is the Global Interpreter Lock (GIL) in Python?
The Global Interpreter Lock (GIL) is a mechanism in the CPython interpreter (the reference
implementation of Python) that allows only one thread to execute Python bytecode at a
time. This restricts the parallel execution of Python threads and can impact performance in
certain scenarios.
55. What is a metaclass in Python?
A metaclass in Python is a class that defines the behavior and structure of other classes. It
allows you to customize class creation, modify attributes, and add additional functionality to
classes.
56. How do you handle file I/O errors in Python?
File I/O errors in Python can be handled using exception handling. By using try-except
blocks around file-related operations, you can catch specific exceptions like
FileNotFoundError or PermissionError and handle them gracefully.
57. What is the purpose of the __name__ variable in Python?
The __name__ variable in Python is a built-in variable that represents the current module's
name. It can be used to determine whether a module is being run as the main script or
imported as a module.
58. What is the difference between a shallow comparison and a deep comparison in Python?
In Python, a shallow comparison checks if two objects have the same memory address,
while a deep comparison checks if the objects have the same values. Shallow comparisons
can be done using the is operator, while deep comparisons are typically done using the ==
operator.
59. What are the advantages of using virtual environments in Python?
Virtual environments in Python provide a dedicated environment for each project, allowing
you to isolate project dependencies, avoid conflicts between packages, and maintain
project-specific versions of Python and packages.
60. What is the purpose of the __main__ block in Python?
The __main__ block in Python is used to define the entry point of a Python program. The
code inside the if __name__ == "__main__": block will only execute if the script is run directly,
not when it is imported as a module.
61. What is the purpose of the __str__ method in Python?
The __str__ method in Python is a special method that returns a string representation of an
object. It is used to provide a human-readable representation of the object when the str()
function is called or when the object is printed.
62. What is the purpose of the __repr__ method in Python?
The __repr__ method in Python is a special method that returns a string representation of
an object that can be used to recreate the object. It is used to provide a detailed and
unambiguous representation of the object.
63. What is the difference between the __str__ and __repr__ methods in Python?
The __str__ method is intended to provide a human-readable string representation of an
object, while the __repr__ method is intended to provide a detailed and unambiguous string
representation that can be used to recreate the object.
64. What is the purpose of the super() function in Python?
The super() function in Python is used to call a method in a superclass or parent class. It is
often used in method overriding to invoke the superclass's implementation of the method
before adding additional functionality in the subclass.
65. What is the purpose of the __getitem__ method in Python?
The __getitem__ method in Python is a special method that allows objects to define
behavior for indexing and slicing operations. It is called when an item is accessed using
square brackets ([]) and supports accessing items by index or slicing.
66. What is the purpose of the __setitem__ method in Python?
The __setitem__ method in Python is a special method that allows objects to define
behavior for assigning values to items using square brackets ([]). It is called when an item is
assigned a value using indexing.
67. What is the purpose of the __len__ method in Python?
The __len__ method in Python is a special method that returns the length of an object. It is
called when the len() function is used on an object.
68. What is the purpose of the __iter__ method in Python?
The __iter__ method in Python is a special method that returns an iterator object. It is used
to make an object iterable, meaning it can be looped over using a for loop or used with other
iterator-related functions and constructs.
69. What is the purpose of the __next__ method in Python?
The __next__ method in Python is a special method that returns the next item in an iterator.
It is called by the next() function and is used in conjunction with the __iter__ method to
create custom iterators.
70. What is the purpose of the @property decorator in Python?
The @property decorator in Python is used to define a method as a getter for a class
attribute. It allows accessing the attribute as if it were a normal attribute, while internally
calling the getter method.
71. What is the purpose of the @staticmethod decorator in Python?
The @staticmethod decorator in Python is used to define a static method in a class. Static
methods do not require an instance of the class to be called and can be accessed directly
from the class itself.
72. What is the purpose of the @classmethod decorator in Python?
The @classmethod decorator in Python is used to define a class method. Class methods
receive the class itself as the first parameter, allowing them to access and modify class-
level attributes and perform operations specific to the class.
73. What is the purpose of the __call__ method in Python?
The __call__ method in Python is a special method that allows an object to be called as if it
were a function. It is called when parentheses are used to invoke the object.
74. What is the purpose of the *args and **kwargs parameters in Python?
The *args parameter in Python allows a function to accept a variable number of positional
arguments as a tuple, while the **kwargs parameter allows a function to accept a variable
number of keyword arguments as a dictionary. This flexibility allows functions to handle
different numbers and types of arguments.
75. What are decorators in Python?
Decorators in Python are a way to modify or enhance the behavior of functions or classes
without directly modifying their source code. Decorators are implemented as functions that
wrap around the target function or class and add additional functionality.
76. What is the purpose of the @classmethod decorator in Python?
The @classmethod decorator in Python is used to define a class method. Class methods
receive the class itself as the first parameter, allowing them to access and modify class-
level attributes and perform operations specific to the class.
77. What is a lambda function in Python?
A lambda function in Python is an anonymous function that can be defined in a single line. It
is often used for simple, one-time operations and does not require a formal def statement.
78. What are modules in Python?
Modules in Python are files that contain Python code and definitions. They can be imported
and used in other Python programs to provide reusable functionality.
79. What are packages in Python?
Packages in Python are a way to organize related modules into a directory hierarchy. They
allow for better organization and modularization of code, making it easier to manage large
projects.
80. What is the purpose of the __init__.py file in a package?
The __init__.py file in a package serves as an indicator that the directory is a Python
package. It can be empty or contain initialization code that is executed when the package is
imported.
81. What is the purpose of the sys module in Python?
The sys module in Python provides access to system-specific parameters and functions. It
allows interaction with the Python interpreter and provides information about the runtime
environment.
82. What is the purpose of the os module in Python?
The os module in Python provides a way to interact with the operating system. It allows
performing various operations related to file and directory manipulation, process
management, and environment variables.
83. What is the purpose of the datetime module in Python?
The datetime module in Python provides classes for manipulating dates and times. It allows
creating, formatting, and performing operations on dates and times.
84. What are decorators in Python?
Decorators in Python are a way to modify or enhance the behavior of functions or classes
without directly modifying their source code. Decorators are implemented as functions that
wrap around the target function or class and add additional functionality.
85. What is the purpose of the @property decorator in Python?
The @property decorator in Python is used to define a method as a getter for a class
attribute. It allows accessing the attribute as if it were a normal attribute, while internally
calling the getter method.
86. What is the purpose of the @staticmethod decorator in Python?
The @staticmethod decorator in Python is used to define a static method in a class. Static
methods do not require an instance of the class to be called and can be accessed directly
from the class itself.
87. What is the purpose of the @classmethod decorator in Python?
The @classmethod decorator in Python is used to define a class method. Class methods
receive the class itself as the first parameter, allowing them to access and modify class-
level attributes and perform operations specific to the class.
88. What is a lambda function in Python?
A lambda function in Python is an anonymous function that can be defined in a single line. It
is often used for simple, one-time operations and does not require a formal def statement.
89. What are modules in Python?
Modules in Python are files that contain Python code and definitions. They can be imported
and used in other Python programs to provide reusable functionality.
90. What are packages in Python?
Packages in Python are a way to organize related modules into a directory hierarchy. They
allow for better organization and modularization of code, making it easier to manage large
projects.
91. What is the purpose of the __init__.py file in a package?
The __init__.py file in a package serves as an indicator that the directory is a Python
package. It can be empty or contain initialization code that is executed when the package is
imported.
92. What is the purpose of the sys module in Python?
The sys module in Python provides access to system-specific parameters and functions. It
allows interaction with the Python interpreter and provides information about the runtime
environment.
93. What is the purpose of the os module in Python?
The os module in Python provides a way to interact with the operating system. It allows
performing various operations related to file and directory manipulation, process
management, and environment variables.
94. What is the purpose of the datetime module in Python?
The datetime module in Python provides classes for manipulating dates and times. It allows
creating, formatting, and performing operations on dates and times.
95. What is the purpose of the random module in Python?
The random module in Python provides functions for generating random numbers. It allows
you to generate random integers, floating-point numbers, and make random selections
from lists.
96. What is the purpose of the json module in Python?
The json module in Python provides functions for working with JSON (JavaScript Object
Notation) data. It allows encoding Python objects into JSON strings and decoding JSON
strings into Python objects.
97. What is the purpose of the pickle module in Python?
The pickle module in Python provides functions for serializing and deserializing Python
objects. It allows you to convert Python objects into a binary format that can be stored or
transmitted, and then restore them back into objects.
98. What are generators in Python?
Generators in Python are functions that can be paused and resumed, allowing them to
produce a sequence of values over time. They are memory-efficient and provide a
convenient way to iterate over large or infinite sequences.
99. What is the purpose of the yield keyword in Python?
The yield keyword in Python is used in the context of generators. It allows a generator
function to temporarily pause and yield a value to the caller, without losing its internal state.
The generator can then be resumed to continue execution from where it left off.
100. What is the purpose of the zip() function in Python?
The zip() function in Python is used to combine multiple iterables (such as lists or tuples) into
a single iterable of tuples. It pairs up corresponding elements from each iterable, stopping
when the shortest iterable is exhausted.
100 Most Asked HTML
QnA
Made By:
1. What is HTML?
a. HTML stands for Hypertext Markup Language. It is the standard markup language
used for creating web pages.
2. What are the basic building blocks of HTML?
a. The basic building blocks of HTML are tags, which are used to structure and define
the content of a web page.
3. What is the DOCTYPE declaration in HTML?
a. The DOCTYPE declaration is used to specify the version of HTML that the web page
is written in. It helps the browser render the page correctly.
4. What is the difference between HTML elements, tags, and attributes?
a. HTML elements are the individual components that make up a web page, such as
headings, paragraphs, and images. Tags are used to mark the beginning and end
of HTML elements. Attributes provide additional information or modify the behavior
of HTML elements.
5. What are some common HTML tags?
a. Some common HTML tags include <h1> to <h6> for headings, <p> for paragraphs,
<a> for links, <img> for images, <ul> and <li> for unordered lists, and <table> for
tables.
6. What is the purpose of the <head> tag in HTML?
a. The <head> tag is used to contain meta-information about the HTML document,
such as the title, character encoding, and linked stylesheets or scripts.
7. What is the purpose of the <body> tag in HTML?
a. The <body> tag is used to define the main content of the HTML document that is
displayed in the browser.
8. What is the difference between block-level elements and inline elements?
a. Block-level elements start on a new line and take up the full width available, while
inline elements do not start on a new line and only take up the necessary width to
display the content.
9. What is the purpose of the <div> tag in HTML?
a. The <div> tag is a container used to group and style HTML elements. It is commonly
used for layout and organization purposes.
10. What is the purpose of the <span> tag in HTML?
a. The <span> tag is an inline container used to apply styles or manipulate specific
portions of text within a larger block of content.
11. What is the purpose of the <a> tag in HTML?
a. The <a> tag is used to create hyperlinks to other web pages, files, or locations
within the same page.
12. What is the purpose of the href attribute in the <a> tag?
a. The href attribute specifies the URL or destination of the hyperlink.
13. What is the purpose of the <img> tag in HTML?
a. The <img> tag is used to display images on a web page.
14. What is the purpose of the src attribute in the <img> tag?
a. The src attribute specifies the source file or URL of the image.
15. What is the purpose of the <table> tag in HTML?
a. The <table> tag is used to create tabular data with rows and columns.
16. What are the <thead>, <tbody>, and <tfoot> tags used for?
a. The <thead> tag is used to group the header content in a table. The <tbody> tag is
used to group the body content, and the <tfoot> tag is used to group the footer
content.
17. What is the purpose of the <tr> tagin HTML?
18. The <tr> tag is used to define a row in a table.
19. What is the purpose of the <th> and <td> tags in HTML?
a. The <th> tag is used to define a header cell in a table, while the <td> tag is used to
define a data cell.
20. What is the purpose of the colspan and rowspan attributes in the <td> and <th>
tags?
a. The colspan attribute specifies the number of columns a cell should span, and the
rowspan attribute specifies the number of rows a cell should span.
21. What is the purpose of the <form> tag in HTML?
a. The <form> tag is used to create an interactive form on a web page to collect user
input.
22. What are some commonly used form elements in HTML?
a. Some commonly used form elements include <input> for text input, checkboxes,
and radio buttons, <select> for dropdown lists, and <textarea> for multiline text
input.
23. What is the purpose of the name attribute in form elements?
a. The name attribute is used to identify form elements and is used to retrieve their
values on the server side.
24. What is the purpose of the method attribute in the <form> tag?
a. The method attribute specifies the HTTP method used to send form data to the
server. The most common values are "GET" and "POST".
25. What is the purpose of the action attribute in the <form> tag?
a. The action attribute specifies the URL or destination where the form data should be
sent.
26. What is the purpose of the <input> tag in HTML?
a. The <input> tag is used to create various types of form input fields, such as text
fields, checkboxes, radio buttons, and submit buttons.
27. What is the purpose of the type attribute in the <input> tag?
a. The type attribute specifies the type of input field to be created, such as "text",
"checkbox", "radio", "submit", etc.
28. What is the purpose of the <label> tag in HTML?
a. The <label> tag is used to associate a text label with a form element. It improves
accessibility and allows users to click on the label to activate the associated form
element.
29. What is the purpose of the <select> tag in HTML?
a. The <select> tag is used to create a dropdown list of options for users to choose
from.
30. What is the purpose of the <option> tag in the <select> tag?
a. The <option> tag is used to define an option within a dropdown list.
31. What is the purpose of the value attribute in the <option> tag?
a. The value attribute specifies the value associated with an option. It is sent to the
server when the form is submitted.
32. What is the purpose of the <textarea> tag in HTML?
a. The <textarea> tag is used to create a multiline text input field where users can
enter larger blocks of text.
33. What is the purpose of the <iframe> tag in HTML?
a. The <iframe> tag is used to embed another web page or document within the
current HTML document.
34. What is the purpose of the <div> tag in HTML?
a. The <div> tag is a container used to group and style HTML elements. Itis commonly
used for layout and organization purposes.
35. What is the purpose of the <span> tag in HTML?
a. The <span> tag is an inline container used to apply styles or manipulate specific
portions of text within a larger block of content.
36. What is the purpose of the <audio> and <video> tags in HTML?
a. The <audio> tag is used to embed audio content on a web page, and the <video>
tag is used to embed video content. They provide built-in controls for playing and
pausing the media.
37. What is the purpose of the <canvas> tag in HTML?
a. The <canvas> tag is used to draw graphics, animations, and other visualizations on
a web page using JavaScript.
38. What is the purpose of the <header>, <main>, <footer>, and <nav> tags in HTML?
a. The <header> tag is used to define the header section of a web page. The <main>
tag is used to define the main content area. The <footer> tag is used to define the
footer section, and the <nav> tag is used to define the navigation section.
39. What is the purpose of the <article> and <section> tags in HTML?
a. The <article> tag is used to define an independent, self-contained content section
that can be distributed and reused. The <section> tag is used to define a section of
related content within an HTML document.
40. What is the purpose of the <aside> tag in HTML?
a. The <aside> tag is used to define content that is related to the main content but
can be considered separate from it, such as sidebars or pull-out quotes.
41. What is the purpose of the <figure> and <figcaption> tags in HTML?
a. The <figure> tag is used to encapsulate self-contained content, such as images,
diagrams, or videos, along with an optional caption defined using the <figcaption>
tag.
42. What is semantic HTML?
a. Semantic HTML is the practice of using HTML elements that accurately describe the
meaning or purpose of the content they contain. It improves accessibility, search
engine optimization, and code readability.
43. What are the advantages of using external CSS stylesheets?
a. Some advantages of using external CSS stylesheets include easier maintenance,
consistent styling across multiple pages, better separation of concerns (HTML for
structure, CSS for presentation), and faster page loading times due to browser
caching.
44. What is the purpose of the class attribute in HTML?
a. The class attribute is used to assign one or more class names to an HTML element.
It allows for targeted styling and JavaScript manipulation.
45. What is the purpose of the id attribute in HTML?
a. The id attribute is used to assign a unique identifier to an HTML element. It is used
for targeting specific elements with CSS or JavaScript.
46. What is the purpose of the CSS display property?
a. The display property is used to control how an element is rendered and displayed
in the browser. It can change an element's behavior from block to inline, or vice
versa.
47. What is the purpose of the CSS position property?
a. The position property is used to specify the positioning method of an element on
the web page. It can be set to static, relative, absolute, or fixed.
48. What is the purpose of the CSS float property?
a. The float property is used to align an element to theleft or right of its container,
allowing other content to wrap around it.
49. What is the purpose of the CSS box-sizing property?
a. The box-sizing property is used to control how the width and height of an element
are calculated. It can be set to content-box (default) or border-box.
50. What is the purpose of the CSS flexbox layout?
a. The CSS flexbox layout is a flexible box layout model that allows you to create
responsive and flexible layouts. It provides powerful tools for arranging and
aligning elements within a container.
51. What is the purpose of the CSS grid layout?
a. The CSS grid layout is a two-dimensional layout model that allows you to create
complex grid-based layouts. It provides precise control over the positioning and
alignment of elements.
52. What is the purpose of the <meta> tag in HTML?
a. The <meta> tag is used to provide metadata about an HTML document, such as
the character encoding, viewport settings, or author information.
53. What is the purpose of the viewport meta tag in HTML?
a. The viewport meta tag is used to control the width and scaling of the viewport on
mobile devices. It ensures that web pages are displayed correctly and
responsively on different screen sizes.
54. What is the purpose of the alt attribute in the <img> tag?
a. The alt attribute is used to provide alternative text for an image. It is displayed if
the image cannot be loaded or for accessibility purposes.
55. What is the purpose of the title attribute in HTML?
a. The title attribute is used to provide additional information or a tooltip text for an
element. It is displayed when the user hovers over the element.
56. What is the purpose of the <fieldset> and <legend> tags in HTML?
a. The <fieldset> tag is used to group related form elements together, and the
<legend> tag is used to provide a caption or description for the <fieldset>.
57. What is the purpose of the <datalist> tag in HTML?
a. The <datalist> tag is used to provide a list of predefined options for an <input> field.
It provides suggestions as the user types.
58. What is the purpose of the <meter> tag in HTML?
a. The <meter> tag is used to represent a scalar measurement within a known range,
such as a progress bar, disk usage, or temperature.
59. What is the purpose of the <time> tag in HTML?
a. The <time> tag is used to represent a specific time or date. It can be used for
machine-readable dates, event schedules, or time-related content.
60. What is the purpose of the required attribute in form elements?
a. The required attribute is used to specify that a form input field must be filled out
before submitting the form.
61. What is the purpose of the autocomplete attribute in form elements?
a. The autocomplete attribute is used to control whether a form input field should
have autocomplete suggestions or not.
62. What is the purpose of the <nav> tag in HTML?
a. The <nav> tag is used to define a section of a web page that contains navigation
links.
63. What is the purpose of the <abbr> tag in HTML?
a. The <abbr> tag is used to define an abbreviation or acronym. It can provide
additional information when the user hovers over it.
The <pre> tag is used to display preformatted text, preserving both spaces and line breaks
as they appear in the HTML code.
The disabled attribute is used to make a form input field or button non-editable or non-
clickable. It prevents user interaction with the element.
The readonly attribute is used to make a form input field non-editable. It allows the user to
view the value but not modify it.
The <progress> tag is used to represent the progress of a task or the completion of a
process, such as a file upload or a download.
What is the purpose of the placeholder attribute in form elements?
The placeholder attribute is used to provide a hint or example value for a form input field.
It is displayed in the field until the user enters their own value.
The <ruby> tag is used to annotate or provide pronunciation guidance for characters in
East Asian typography. The <rt> tag is used to define the pronunciation of the characters.
The <bdi> tag is used to isolate a section of text that is to be formatted in a different
direction from its surrounding text. It is often used for multilingual content.
The <details> tag is used to create a collapsible section that can be toggled open or
closed. The <summary> tag is used to provide a summary or heading for the collapsible
section.
The <wbr> tag is used to suggest a line break opportunity within a word. It is used to
control word wrapping in long URLs or strings without adding unnecessary spaces.
The contenteditable attribute is used to make an element editable by the user. It allows
the user to modify the content directly in the browser.
The spellcheck attribute is used to enable or disable spell checking for a form input field.
The <cite> tag is used to mark a reference to a creative work, such as a book, article, or
movie title.
The download attribute is used to specify that a hyperlink should be downloaded instead
of navigated to when clicked. It specifies the filename of the downloaded file.
What is the purpose of the <script> tag in HTML?
The <script> tag is used to embed or reference JavaScript code within an HTML document.
Inline JavaScript is directly embedded within the HTML document using the <script> tag,
while external JavaScript is saved in a separate .js file and linked to the HTML document
using the src attribute of the <script> tag.
The <noscript> tag is used to provide an alternative content that should be displayed if a
web browser does not support or has disabled JavaScript.
The defer attribute is used to indicate that the script should be executed after the
document has been parsed, allowing it to not block rendering.
The async attribute is used to indicate that the script can be executed asynchronously,
without blocking the rendering of the page.
The <iframe> tag is used to embed another web page or document within the current
HTML document.
The sandbox attribute is used to restrict the capabilities of the content within the <iframe>,
providing a secure and isolated environment.
The <datalist> tag is used to provide a list of predefined options for an <input> field. It
provides suggestions as the user types.
The autocomplete attribute is used to control whether a form input field should have
autocomplete suggestions or not.
What is the purpose of the <figure> and <figcaption> tags in HTML?
The <meter> tag is used to represent a scalar measurement within a known range, such
as a progress bar, disk usage, or temperature.
The <time> tag is used to represent a specific time or date. It can be used for machine-
readable dates, event schedules, or time-related content.
The required attribute is used to specify that a form input field must be filled out before
submitting the form.
The autocomplete attribute is used to control whether a form input field should have
autocomplete suggestions or not.
The <nav> tag is used to define a section of a web page that contains navigation links.
The <abbr> tag is used to define an abbreviation or acronym. It can provide additional
information when the user hovers over it.
The <pre> tag is used to display preformatted text, preserving both spaces and line breaks
as they appear in the HTML code.
The disabled attribute is used to make a form input field or button non-editable or non-
clickable. It prevents user interaction with the element.
What is the purpose of the readonly attribute in formelements?
The readonly attribute is used to make a form input field non-editable. It allows the user to
view the value but not modify it.
The <progress> tag is used to represent the progress of a task or the completion of a
process, such as a file upload or a download.
The placeholder attribute is used to provide a hint or example value for a form input field.
It is displayed in the field until the user enters their own value.
The <ruby> tag is used to annotate or provide pronunciation guidance for characters in
East Asian typography. The <rt> tag is used to define the pronunciation of the characters.
The <bdi> tag is used to isolate a section of text that is to be formatted in a different
direction from its surrounding text. It is often used for multilingual content.
The <details> tag is used to create a collapsible section that can be toggled open or
closed. The <summary> tag is used to provide a summary or heading for the collapsible
section.
2. What is an array?
An array is a data structure that stores a fixed-size sequence of elements of the same
type. It provides random access to its elements using an index. Arrays are commonly
used for storing and manipulating collections of data, such as a list of integers or
characters.
A linked list is a data structure in which each element, called a node, contains a value
and a reference to the next node in the sequence. Unlike arrays, linked lists do not require
contiguous memory allocation, allowing for efficient insertion and deletion operations.
However, accessing elements in a linked list requires traversing the list from the
beginning.
4. What is a stack?
A stack is an abstract data type that follows the Last-In-First-Out (LIFO) principle. It
supports two main operations: push (inserting an element onto the top of the stack) and
pop (removing the topmost element from the stack). Stacks are often used for
managing function calls, expression evaluation, and undo mechanisms.
5. What is a queue?
A queue is an abstract data type that follows the First-In-First-Out (FIFO) principle. It
supports two primary operations: enqueue (adding an element to the end of the queue)
and dequeue (removing the element at the front of the queue). Queues are commonly
used in scenarios where data needs to be processed in the order it arrives, such as
scheduling tasks or handling requests.
6. What is a tree?
A tree is a hierarchical data structure consisting of nodes connected by edges. It has a
root node at the top and child nodes below it, forming a branching structure. Trees are
used to represent hierarchical relationships, such as file systems, organization structures,
and decision-making processes.
7. What is a graph?
A graph is a non-linear data structure consisting of nodes (vertices) and edges that
connect them. It is a powerful tool for representing relationships between objects. Graphs
can be directed (edges have a specific direction) or undirected (edges have no
direction). They are widely used in network analysis, social networks, and pathfinding
algorithms.
The main difference between an array and a linked list is their underlying structure and
the operations they support. Arrays have contiguous memory allocation and provide
direct access to elements using an index, allowing for fast random access. Linked lists, on
the other hand, use nodes with references to the next element, providing efficient
insertion and deletion at any position but slower access time.
The key difference between a stack and a queue lies in their order of operations. A stack
follows the Last-In-First-Out (LIFO) principle, where the last element inserted is the first
one to be removed. In contrast, a queue adheres to the First-In-First-Out (FIFO) principle,
where the first element inserted is the first one to be removed. Stacks are like a pile of
plates, while queues resemble a line of people waiting.
While both trees and graphs are hierarchical structures, the main difference lies in their
level of organization. A tree is a type of graph that does not contain cycles, meaning
there are no loops or circular dependencies among the nodes. In contrast, a general
graph can have cycles and arbitrary connections between nodes, allowing for more
complex relationships.
11. What is the difference between breadth-first search (BFS) and depth-first search
(DFS)?
Breadth-first search (BFS) and depth-first search (DFS) are graph traversal algorithms
that visit all the nodes in a graph. The key difference is the order in which they explore the
nodes. BFS visits all the neighbors of a node before moving to the next level, resembling a
wave expanding from the starting point. DFS explores as far as possible along each
branch before backtracking, going deeper into the graph.
The time complexity of searching for an element in an array depends on the search
algorithm used. The simplest approach is linear search, which has a time complexity of
O(n), where n is the number of elements in the array. Binary search, on the other hand,
has a time complexity of O(log n) if the array is sorted, as it repeatedly divides the
search space in half.
14. What is the time complexity of inserting an element into a linked list?
Inserting an element into a linked list typically involves updating the references of the
adjacent nodes. If the insertion happens at the beginning or end of the linked list, the
time complexity is constant, O(1), as it requires updating only a few references. However,
inserting in the middle of a linked list requires traversing it until the desired position,
resulting in a time complexity of O(n), where n is the number of elements in the linked
list.
15. What is the time complexity of searching for an element in a linked list?
The time complexity of searching for an element in a linked list is O(n), where n is the
number of elements in the linked list. Since linked lists do not provide random access, we
need to traverse the list from the beginning until we find the desired element or reach the
end. This linear traversal makes the search time proportional to the size of the linked list.
A binary search tree (BST) is a binary tree data structure in which each node has a
key/value and follows a specific property: the key of any node in the left subtree is less
than the key of the node itself, and the key of any node in the right subtree is greater. This
property allows for efficient searching, insertion, and deletion operations, with an
average time complexity of O(log n), where n is the number of nodes in the tree.
A heap is a complete binary tree data structure that satisfies the heap property: for a
max heap, the key of each node is greater than or equal to the keys of its children; for a
min heap, the key of each node is smaller than or equal to the keys of its children. Heaps
are commonly used to implement priority queues and efficient sorting algorithms like
heap sort.
Arrays and hash tables differ in their underlying structure and the operations they
support. Arrays provide direct access to elements using an index, allowing for fast
random access. In contrast, hash tables use a hash function to map keys to values,
providing efficient insertion, deletion, and retrieval operations, but without direct index-
based access.
20. What is the time complexity of inserting an element into a hash table?
The time complexity of inserting an element into a hash table is typically O(1), assuming
a well-designed hash function and an evenly distributed hash table. The hash function
calculates the index where the element will be stored, and the element is inserted at that
position. In the best case, insertion can be constant time. However, in the worst case,
when collisions occur and chaining is used to resolve them, the time complexity can be
O(n), where n is the number of elements in the hash table.
21. What is the time complexity of searching for an element in a hash table?
The time complexity of searching for an element in a hash table is typically O(1),
assuming a well-designed hash function and an evenly distributed hash table. The hash
function calculates the index of the element, and a lookup is performed at that position.
In the best case, the element is found immediately. However, in the worst case, when
collisions occur and chaining is used, the time complexity can be O(n), where n is the
number of elements in the hash table.
A trie, also known as a prefix tree, is a tree-based data structure used to efficiently store
and search for strings. Each node in the trie represents a common prefix of multiple
strings, and the edges represent individual characters. Tries are particularly useful for
tasks such as autocomplete, spell checking, and IP routing.
The time complexity of inserting a string into a trie is proportional to the length of the
string, denoted as O(m), where m is the length of the string. During insertion, the
algorithm traverses the trie, creating new nodes as necessary until the entire string is
inserted. The efficiency of tries lies in their ability to provide fast prefix-based searches.
The time complexity of searching for a string in a trie is proportional to the length of the
string, denoted as O(m), where m is the length of the string. The algorithm follows the
characters of the string, traversing the trie from the root to the corresponding leaf node. If
the string exists in the trie, the search operation terminates at the leaf node. Otherwise, it
reaches a point where the string is not present.
A divide and conquer algorithm breaks down a problem into smaller, more manageable
subproblems, solves them independently, and combines the solutions to obtain the final
solution. It follows the recursive structure of dividing the problem, solving the
subproblems, and merging the results. Divide and conquer algorithms are often used in
sorting (e.g., merge sort, quicksort) and searching (e.g., binary search) problems.
A dynamic array, also known as a resizable array, is a data structure that provides the
flexibility of resizing the array during runtime. It starts with a fixed initial capacity and
dynamically allocates more memory when needed. Dynamic arrays combine the
benefits of arrays, such as constant-time random access, with the ability to grow or
shrink the array as necessary.
32. What is the time complexity of removing an element from a dynamic array?
The time complexity of removing an element from a dynamic array depends on the
position of the element. If the element is removed from the end of the array, the time
complexity is constant, O(1), as it only requires updating the array's size. However, if the
element is removed from the middle, all subsequent elements need to be shifted,
resulting in a time complexity of O(n), where n is the number of elements in the array.
34. What is the time complexity of inserting an element into a red-black tree?
The time complexity of inserting an element into a red-black tree is O(log n), where n is
the number of nodes in the tree. The balancing operations performed during insertion
take logarithmic time because the tree height remains balanced, thanks to the red-
black tree properties. The self-balancing nature ensures that the worst-case height of
the tree remains proportional to log n.
35. What is the time complexity of searching for an element in a red-black tree?
The time complexity of searching for an element in a red-black tree is O(log n), where n
is the number of nodes in the tree. Similar to other balanced binary search trees, the
height of the red-black tree remains balanced due to its properties. As a result, the
search operation efficiently narrows down the search space, leading to a logarithmic
time complexity.
A B-tree is a self-balancing tree data structure designed to efficiently store and retrieve
large amounts of data on disk or other secondary storage devices. It allows for efficient
operations by minimizing the number of disk accesses required. B-trees are commonly
used in databases and file systems, where data is organized in blocks or pages.
37. What is the time complexity of inserting an element into a B-tree?
The time complexity of inserting an element into a B-tree depends on the height of the
tree. For a B-tree with a balanced structure, the height is logarithmic, resulting in an
average time complexity of O(log n), where n is the number of elements in the tree. The
balancing properties of B-trees ensure that the height remains balanced, leading to
efficient insertions.
The time complexity of searching for an element in a B-tree is similar to the insertion
complexity and depends on the height of the tree. For a balanced B-tree, the height is
logarithmic, resulting in an average time complexity of O(log n), where n is the number
of elements in the tree. The balanced structure ensures efficient search operations by
narrowing down the search space.
A priority queue is an abstract data type that maintains a set of elements, each
associated with a priority. It allows for efficient retrieval of the element with the highest
(or lowest) priority. Priority queues are commonly implemented using binary heaps or
balanced binary search trees. They find applications in scheduling, Dijkstra's algorithm,
and Huffman coding, among others.
40. What is the difference between a priority queue and a regular queue?
The main difference between a priority queue and a regular queue lies in the ordering of
elements. In a regular queue, elements are stored and retrieved in a First-In-First-Out
(FIFO) order. However, in a priority queue, elements are associated with priorities and
retrieved based on the priority order. The element with the highest (or lowest) priority is
dequeued first.
41. What is the time complexity of inserting an element into a priority queue
implemented with a binary heap?
The time complexity of inserting an element into a priority queue implemented with a
binary heap is O(log n), where n is the number of elements in the heap. During insertion,
the element is appended to the end of the heap, and then it "bubbles up" by swapping
with its parent until the heap property is restored. The maximum number of swaps
required is proportional to the height of the heap, which is logarithmic.
42. What is the time complexity of accessing the maximum element in a priority queue
implemented with a binary heap?
The time complexity of removing the maximum element from a priority queue
implemented with a binary heap is O(log n), where n is the number of elements in the
heap. The removal process involves swapping the root with the last element, "bubbling
down" the new root to its proper position, and restoring the heap property. The number of
swaps required is proportional to the height of the heap, which is logarithmic.
44. What is the time complexity of sorting elements using heap sort?
The time complexity of sorting elements using heap sort is O(n log n), where n is the
number of elements in the input array. Heap sort involves building a binary heap from
the array (O(n)), repeatedly removing the maximum element from the heap (O(log n))
and placing it in the sorted portion of the array. The overall time complexity is dominated
by the O(log n) removal operation, performed n times.
A graph traversal algorithm explores all the nodes or vertices of a graph in a systematic
manner. It enables visiting each node and performing necessary operations, such as
marking the node as visited or collecting information. Common graph traversal
algorithms include depth-first search (DFS) and breadth-first search (BFS).
46. What is the difference between BFS and DFS graph traversal algorithms?
The main difference between breadth-first search (BFS) and depth-first search (DFS) lies
in the order in which they explore nodes in a graph. BFS visits all the neighbors of a node
before moving to the next level, resembling a wave expanding from the starting point.
DFS explores as far as possible along each branch before backtracking, going deeper
into the graph. As a result, BFS typically finds the shortest path, while DFS explores paths
deeply.
The time complexity of breadth-first search (BFS) in a graph is O(V + E), where V is the
number of vertices (nodes) and E is the number of edges in the graph. BFS visits each
vertex once and examines all its adjacent edges, resulting in a linear time complexity.
The time complexity of depth-first search (DFS) in a graph is O(V + E), where V is the
number of vertices (nodes) and E is the number of edges in the graph. DFS visits each
vertex once and examines all its adjacent edges recursively, resulting in a linear time
complexity.
A topological sort is an ordering of the vertices in a directed acyclic graph (DAG) such
that for every directed edge (u, v), vertex u comes before vertex v in the ordering.
Topological sorting is commonly used in tasks such as task scheduling, dependency
resolution, and determining the order of events.
50. What is the time complexity of topological sort in a directed acyclic graph?
The time complexity of topological sort in a directed acyclic graph (DAG) is O(V + E),
where V is the number of vertices (nodes) and E is the number of edges in the graph. The
algorithm performs a depth-first search (DFS) with some modifications, resulting in a
linear time complexity.
A linked list is a linear data structure consisting of nodes, where each node contains a
value and a reference (or pointer) to the next node in the sequence. Linked lists allow for
efficient insertion and deletion at any position, but accessing elements requires
traversing the list from the beginning.
52. What is the time complexity of inserting an element at the beginning of a linked list?
The time complexity of inserting an element at the beginning of a linked list is O(1). Since
the new element becomes the head of the list, it simply requires updating the head
pointer to point to the new node.
53. What is the time complexity of inserting an element at the end of a linked list?
The time complexity of inserting an element at the end of a linked list is O(n), where n is
the number of nodes in the list. To insert at the end, we need to traverse the entire list to
reach the last node and then update its reference to point to the new node.
54. What is the time complexity of searching for an element in a linked list?
The time complexity of searching for an element in a linked list is O(n), where n is the
number of nodes in the list. In the worst case, we may need to traverse the entire list to
find the desired element.
55. What is the time complexity of removing an element from a linked list?
The time complexity of removing an element from a linked list depends on the position of
the element. If the element is at the beginning, the removal operation can be done in
O(1) time by updating the head pointer. If the element is in the middle or at the end, it
requires traversing the list to find the element (O(n)) and updating the references
accordingly.
A stack is an abstract data type that follows the Last-In-First-Out (LIFO) principle. It can
be visualized as a vertical stack of elements, where insertion and deletion occur only at
one end, known as the top. The last element inserted is the first one to be removed.
The time complexity of removing (popping) an element from a stack is O(1). It involves
removing the element from the top of the stack by updating the top pointer.
59. What is the time complexity of accessing the top element of a stack?
The time complexity of accessing (peeking) the top element of a stack is O(1). It involves
retrieving the element from the top of the stack without modifying the stack itself.
A queue is an abstract data type that follows the First-In-First-Out (FIFO) principle. It can
be visualized as a horizontal line of elements, where insertion occurs at one end (rear)
and removal occurs at the other end (front). The first element inserted is the first one to
be removed.
The time complexity of inserting (enqueueing) an element into a queue is O(1). It involves
adding the element to the rear of the queue.
63. What is the time complexity of accessing the front element of a queue?
The time complexity of accessing (peeking) the front element of a queue is O(1). It
involves retrieving the element from the front of the queue without modifying the queue
itself.
A hash table is a data structure that implements an associative array abstract data
type. It uses a hash function to map keys to array indices, allowing for efficient insertion,
deletion, and retrieval of key-value pairs. Hash tables provide constant-time average
case complexity for these operations.
A hash function is a function that takes an input (such as a key) and returns a fixed-size
numerical value, known as a hash code or hash value. The hash function is designed to
evenly distribute the hash codes across the available indices of the hash table,
minimizing collisions and maximizing efficiency.
67. What is the time complexity of inserting an element into a hash table?
The time complexity of inserting an element into a hash table is typically O(1) on
average. However, in the worst case, when collisions are frequent and extensive chaining
or probing is required, the time complexity can increase to O(n), where n is the number
of elements in the hash table.
68. What is the time complexity of retrieving an element from a hash table?
The time complexity of retrieving an element from a hash table is typically O(1) on
average. However, in the worst case, when collisions are frequent and extensive chaining
or probing is involved, the time complexity can increase to O(n), where n is the number
of elements in the hash table.
69. What is the time complexity of removing an element from a hash table?
The time complexity of removing an element from a hash table is typically O(1) on
average. However, in the worst case, when collisions are frequent and extensive chaining
or probing is required, the time complexity can increase to O(n), where n is the number
of elements in the hash table.
A binary search tree (BST) is a binary tree data structure in which each node has a key
greater than all the keys in its left subtree and smaller than all the keys in its right
subtree. This property enables efficient searching, insertion, and deletion operations. In-
order traversal of a BST yields a sorted sequence of keys.
71. What is the time complexity of searching for an element in a binary search tree
(BST)?
The time complexity of searching for an element in a binary search tree (BST) is O(h),
where h is the height of the tree. In a balanced BST, the height is logarithmic (h = log n,
where n is the number of nodes), resulting in an average case time complexity of O(log
n). However, in the worst case, when the tree is skewed and resembles a linked list, the
height is linear (h = n), leading to a time complexity of O(n).
72. What is the time complexity of inserting an element into a binary search tree (BST)?
The time complexity of inserting an element into a binary search tree (BST) is O(h),
where h is the height of the tree. In a balanced BST, the height is logarithmic (h = log n,
where n is the number of nodes), resulting in an average case time complexity of O(log
n). However, in the worst case, when the tree is skewed and resembles a linked list, the
height is linear (h = n), leading to a time complexity of O(n).
73. What is the time complexity of removing an element from a binary search tree (BST)?
The time complexity of removing an element from a binary search tree (BST) is O(h),
where h is the height of the tree. In a balanced BST, the height is logarithmic (h = log n,
where n is the number of nodes), resulting in an average case time complexity of O(log
n). However, in the worst case, when the tree is skewed and resembles a linked list, the
height is linear (h = n), leading to a time complexity of O(n).
A self-balancing binary search tree is a binary search tree that automatically maintains
a balanced structure during insertions and deletions. It achieves this balance by
performing rotations or other operations to ensure that the height of the tree remains
logarithmic, optimizing the time complexity of search, insert, and delete operations.
An AVL tree is a self-balancing binary search tree named after its inventors, Adelson-
Velsky and Landis. It maintains the balance factor (the height difference between left
and right subtrees) of each node, ensuring that it is always in the range of -1, 0, or 1. AVL
trees perform rotations to maintain balance and achieve efficient operations with a
worst-case time complexity of O(log n).
A red-black tree is a self-balancing binary search tree with an additional color attribute
for each node, either red or black. The color properties and rotations maintain a balance
between the left and right subtrees, ensuring that the longest path is no more than twice
the length of the shortest path. Red-black trees offer efficient operations with a worst-
case time complexity of O(log n).
A heap is a complete binary tree data structure that satisfies the heap property. In a max
heap, for every node, the value of the node is greater than or equal to the values of its
children. In a min heap, the value of each node is smaller than or equal to the values of
its children. Heaps are commonly used to implement priority queues and heap sort.
78. What is the time complexity of finding the maximum (or minimum) element in a
heap?
The time complexity of finding the maximum (or minimum) element in a heap is O(1).
The maximum (or minimum) element is always located at the root of the heap, allowing
for direct access without the need for traversal or comparison with other elements.
80. What is the time complexity of removing the maximum (or minimum) element from
a heap?
The time complexity of removing the maximum (or minimum) element from a heap is
O(log n), where n is the number of elements in the heap. The removal process involves
swapping the root with the last element, removing the last element, and "bubbling down"
the new root by swapping it with its larger (or smaller) child until the heap property is
satisfied. The number of swaps required is proportional to the height of the heap, which is
logarithmic.
A trie, also known as a prefix tree, is a tree-based data structure commonly used for
efficient string searching and retrieval operations. It stores a set of strings, where each
node represents a prefix or a complete string. Trie nodes typically have multiple child
pointers, each associated with a character. Tries are useful in applications such as
autocomplete, spell-checking, and IP routing.
The time complexity of searching for a string in a trie is O(m), where m is the length of
the string. The search process involves traversing the trie from the root to the leaf node
corresponding to the last character of the string. The number of comparisons required is
proportional to the length of the string.
The time complexity of inserting a string into a trie is O(m), where m is the length of the
string. The insertion process involves traversing the trie based on the characters of the
string and creating new nodes as necessary. The number of operations is proportional to
the length of the string.
A directed acyclic graph (DAG) is a directed graph that does not contain any directed
cycles. In other words, it is impossible to traverse from a vertex and return back to it by
following the directions of the edges. DAGs are used in various applications, including
task scheduling, dependency resolution, and representing precedence relationships.
A minimum spanning tree (MST) is a subset of the edges of a weighted undirected graph
that connects all the vertices with the minimum possible total edge weight. MSTs are
used to find the most cost-effective way to connect a set of nodes. Common algorithms
for finding MSTs include Prim's algorithm and Kruskal's algorithm.
Dijkstra's algorithm is a graph traversal algorithm used to find the shortest path between
a starting vertex and all other vertices in a weighted graph with non-negative edge
weights. It maintains a priority queue to continuously select the vertex with the smallest
distance from the starting vertex and updates the distances of adjacent vertices
accordingly. Dijkstra's algorithm guarantees the shortest paths when all edge weights
are non-negative.
The time complexity of Dijkstra's algorithm depends on the data structure used to
implement the priority queue. When implemented with a binary heap or Fibonacci heap,
the time complexity is O((V + E) log V), where V is the number of vertices and E is the
number of edges in the graph.
90. What is the difference between a breadth-first search (BFS) and a depth-first search
(DFS)?
BFS and DFS are graph traversal algorithms with different exploration strategies. BFS
explores all the vertices at the current depth level before moving to the next depth level,
while DFS explores as far as possible along each branch before backtracking. BFS uses a
queue data structure, while DFS uses a stack or recursion.
The time complexity of a recursive algorithm with memoization depends on the number
of distinct subproblems encountered. If there are n subproblems, and the time
complexity of solving each subproblem is O(1), the overall time complexity is O(n).
An array is a contiguous block of memory that stores elements of the same type.
Accessing elements in an array is fast and constant time (O(1)) because they can be
accessed directly using their indices. However, inserting or deleting elements in the
middle of an array requires shifting subsequent elements, resulting in a time complexity
of O(n).
On the other hand, a linked list is a data structure where elements (nodes) are scattered
in memory and connected through pointers. Insertion and deletion operations in a linked
list can be done in constant time (O(1)) by adjusting pointers, but accessing elements
requires traversing the list, resulting in a time complexity of O(n).
A stack follows the Last-In-First-Out (LIFO) principle, allowing insertion and deletion only
at one end (top). The last element inserted is the first one to be removed.
A queue follows the First-In-First-Out (FIFO) principle, allowing insertion at one end
(rear) and deletion at the other end (front). The first element inserted is the first one to be
removed.
96. What is the difference between a hash table and a binary search tree?
A hash table uses a hash function to map keys to array indices and provides constant-
time average case complexity for insertion, deletion, and retrieval operations. However,
hash tables do not naturally maintain order and may experience collisions, affecting
performance.
A binary search tree (BST) maintains elements in a sorted order based on their keys.
BSTs provide efficient searching, insertion, and deletion operations with a time
complexity of O(log n) in balanced trees. However, the time complexity can degrade to
O(n) in worst-case scenarios.
97. What is the difference between a graph and a tree?
A tree is a type of graph that is acyclic (no cycles) and connected. A tree has a root node
and a hierarchical structure where each node has zero or more child nodes. There is a
unique path between any two nodes in a tree.
98. What is the difference between a breadth-first search (BFS) and a depth-first search
(DFS) in a graph?
BFS and DFS are graph traversal algorithms with different exploration strategies:
BFS explores all the vertices at the current depth level before moving to the next
depth level. It uses a queue to store the vertices and visits them in the order of their
discovery.
DFS explores as far as possible along each branch before backtracking. It uses a
stack or recursion to store the vertices and visits them in a depth-first manner.
BFS is typically used to find the shortest path between two vertices or to visit all vertices
in a connected component. DFS is useful for tasks such as finding cycles, topological
sorting, and exploring paths in a graph.
99. What is the difference between a spanning tree and a minimum spanning tree?
A spanning tree of a graph is a subgraph that includes all the vertices of the graph while
forming a tree structure without any cycles. It preserves the connectivity of the original
graph.
A minimum spanning tree (MST) is a spanning tree with the minimum possible total
edge weight. It connects all the vertices with the least overall cost. MSTs are useful in
scenarios such as designing network infrastructure or connecting a set of locations with
minimal expenses.
1. What is SQL?
a. SQL (Structured Query Language) is a programming language used for managing
relational databases. It allows users to store, manipulate, and retrieve data from
databases.
2. What are the different types of SQL statements?
a. SQL statements can be categorized into three types:
i. Data Definition Language (DDL): Used for creating, altering, and dropping
database objects.
ii. Data Manipulation Language (DML): Used for querying, inserting, updating, and
deleting data.
iii. Data Control Language (DCL): Used for controlling access to the database,
granting or revoking privileges.
3. What is a primary key?
a. A primary key is a column or a set of columns that uniquely identifies each record
in a table. It ensures data integrity and allows efficient retrieval of data.
4. What is a foreign key?
a. A foreign key is a column or a set of columns in a table that refers to the primary
key of another table. It establishes a relationship between the two tables.
5. What is a composite key?
a. A composite key is a primary key composed of two or more columns. Together,
these columns uniquely identify each record in a table.
6. What is the difference between DELETE and TRUNCATE?
a. DELETE is a DML statement used to remove specific rows from a table, whereas
TRUNCATE is a DDL statement used to remove all rows from a table, effectively
resetting the table.
7. What is a subquery?
a. A subquery is a query nested within another query. It can be used to retrieve data
from one table based on values from another table or perform complex
calculations.
8. What is the difference between a subquery and a join?
a. A subquery is a query nested within another query, whereas a join is used to
combine rows from two or more tables based on related columns.
9. What is a self-join?
a. A self-join is a join operation where a table is joined with itself. It is useful when
you want to compare rows within the same table.
10. What are the different types of JOIN operations?
a. The different types of JOIN operations are:
i. INNER JOIN: Returns only the matching rows from both tables.
ii. LEFT JOIN: Returns all rows from the left table and matching rows from the right
table.
iii. RIGHT JOIN: Returns all rows from the right table and matching rows from the
left table.
iv. FULL JOIN: Returns all rows from both tables.
11. What is normalization in SQL?
a. Normalization is the process of organizing data in a database to eliminate
redundancy and dependency issues. It involves splitting tables into smaller, more
manageable entities.
12. What are the different normal forms in database normalization?
a. The different normal forms are:
i. First Normal Form (1NF): Eliminates duplicate rows and ensures atomicity of
values.
ii. Second Normal Form (2NF): Ensures that each non-key column depends on the
entire primary key.
iii. Third Normal Form (3NF): Ensures that each non-key column depends only on
the primary key and not on other non-key columns.
iv. Fourth Normal Form (4NF): Eliminates multi-valued dependencies.
v. Fifth Normal Form (5NF): Eliminates join dependencies.
13. What is an index?
a. An index is a database structure that improves the speed of data retrieval
operations on database tables. It allows faster searching, sorting, and filtering of
data.
14. What is a clustered index?
a. A clustered index determines the physical order of data in a table. Each table can
have only one clustered index, and it is generally created on the primary key
column(s).
15. What is a non-clustered index?
a. A non-clustered index is a separate structure from the table that contains a
sorted list of selected columns. It enhances the performance of searching and
filtering operations.
16. What is the difference between a primary key and a unique key?
a. A primary key is a column or a set of columns that uniquely identifies each record
in a table and cannot contain NULL values. A unique key, on the other hand, allows
NULL values and enforces uniqueness but does not automatically define the
primary identifier of a table.
17. What is ACID in database transactions?
a. ACID stands for Atomicity, Consistency, Isolation, and Durability. It is a set of
properties that ensure reliability and integrity in database transactions.
18. What is the difference between UNION and UNION ALL?
a. UNION combines the result sets of two or more SELECT statements and removes
duplicates, whereas UNION ALL combines the result sets without removing
duplicates.
19. What is a view?
a. A view is a virtual table derived from one or more tables. It does not store data but
provides a way to present data in a customized or simplified manner.
20. What is a stored procedure?
a. A stored procedure is a precompiled set of SQL statements that performs a
specific task. It can be called and executed multiple times with different
parameters.
21. What is a trigger?
a. A trigger is a set of SQL statements that are automatically executed in response to
a specific event, such as INSERT, UPDATE, or DELETE operations on a table.
22. What is a transaction?
a. A transaction is a logical unit of work that consists of one or more database
operations. It ensures that all operations within the transaction are treated as a
single unit, either all succeeding or all failing.
23. What is a deadlock?
a. A deadlock is a situation where two or more transactions are unable to proceed
because each is waiting for a resource held by another transaction. This can
result in a perpetual wait state.
24. What is the difference between CHAR and VARCHAR data types?
a. CHAR is a fixed-length character data type that stores a specific number of
characters, while VARCHAR is a variable-length character data type that stores a
varying number of characters.
25. What is the difference between a function and a stored procedure?
a. A function returns a value and can be used in SQL statements, whereas a stored
procedure does not return a value directly but can perform various actions.
26. What is the difference between GROUP BY and HAVING clauses?
a. GROUP BY is used to group rows based on one or more columns, while HAVING is
used to filter grouped rows based on specific conditions.
27. What is the difference between a database and a schema?
a. A database is a collection of related data that is stored and organized. A schema,
on the other hand, is a logical container within a database that holds objects like
tables, views, and procedures.
28. What is a data warehouse?
a. A data warehouse is a large repository of data collected from various sources,
structured and organized to support business intelligence and reporting.
29. What is the difference between OLTP and OLAP?
a. OLTP (Online Transaction Processing) is used for day-to-day transactional
operations and focuses on real-time processing. OLAP (Online Analytical
Processing) is used for complex analytical queries and focuses on historical data
analysis.
30. What is a correlated subquery?
a. A correlated subquery is a subquery that references columns from the outer
query. It is executed for each row of the outer query, making it dependent on the
outer query's results.
31. What is the difference between a temporary table and a table variable?
a. A temporary table is a physical table that is created and used temporarily within
a session or a specific scope, whereas a table variable is a variable with a
structure similar to a table and exists only within the scope of a user-defined
function or a stored procedure.
32. What is the difference between UNION and JOIN?
a. UNION combines rows from two or more tables vertically, while JOIN combines
columns from two or more tables horizontally based on related columns.
33. What is the difference between WHERE and HAVING clauses?
a. WHERE is used to filter rows before grouping in a query, while HAVING is used to
filter grouped rows after grouping.
34. What is the difference between a database and a data warehouse?
a. A database is a collection of related data organized for transactional purposes,
while a data warehouse is a large repository of data organized for analytical
purposes.
35. What is the difference between a primary key and a candidate key?
a. A candidate key is a column or a set of columns that can uniquely identify each
record in a table. A primary key is a chosen candidate key that becomes the main
identifier for the table.
36. What is the difference between a schema and a database?
a. A database is a collection of related data, while a schema is a logical container
within a database that holds objects like tables, views, and procedures.
37. What is a self-join?
a. A self-join is a join operation where a table is joined with itself. It is used when you
want to compare rows within the same table.
38. What is a recursive SQL query?
a. A recursive SQL query is a query that refers to its own output in order to perform
additional operations. It is commonly used for hierarchical or tree-like data
structures.
39. What is the difference between a correlated subquery and a nested subquery?
a. A correlated subquery is a subquery that references columns from the outer
query, while a nested subquery is a subquery that is independent of the outer
query.
40. What is the difference between a natural join and an equijoin?
a. A natural join is a join operation that automatically matches columns with the
same name from both tables, whereas an equijoin is a join operation that
explicitly specifies the join condition using equality operators.
41. What is the difference between an outer join and an inner join?
a. An inner join returns only the matching rows from both tables, whereas an outer
join returns all rows from one table and matching rows from the other table(s).
42. What is the difference between a left join and a right join?
a. A left join returns all rows from the left table and matching rows from the right
table, whereas a right join returns all rows from the right table and matching rows
from the left table.
43. What is a full outer join?
a. A full outer join returns all rows from both tables, including unmatched rows, and
combines them based on the join condition.
44. What is a self-referencing foreign key?
a. A self-referencing foreign key is a foreign key that references the primary key of
the same table. It is used to establish hierarchical relationships within a single
table.
45. What is the purpose of the GROUP BY clause?
a. The GROUP BY clause is used to group rows based on one or more columns. It is
typically used with aggregate functions to perform calculations on each group.
46. What is the purpose of the HAVING clause?
a. The HAVING clause is used to filter grouped rows based on specific conditions. It
operates on the results of the GROUP BY clause.
47. What is the purpose of the ORDER BY clause?
a. The ORDER BY clause is used to sort the result set based on one or more columns
in ascending or descending order.
48. What is the purpose of the DISTINCT keyword?
a. The DISTINCT keyword is used to retrieve unique values from a column in a result
set, eliminating duplicate rows.
49. What is the purpose of the LIKE operator?
a. The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column. It allows wildcard characters like % (matches any sequence of
characters) and _ (matches any single character).
50. What is the purpose of the IN operator?
a. The IN operator is used in a WHERE clause to check if a value matches any value in
a list or a subquery.
51.
What is the purpose of the BETWEEN operator?
a. The BETWEEN operator is used in a WHERE clause to check if a value lies within a
specified range of values, inclusive of the endpoints.
52. What is the purpose of the EXISTS operator?
a. The EXISTS operator is used in a WHERE clause to check if a subquery returns any
rows. It returns true if the subquery result set is not empty.
53. What is the purpose of the COUNT() function?
a. The COUNT() function is used to count the number of rows or non-null values in a
column.
54. What is the purpose of the SUM() function?
a. The SUM() function is used to calculate the sum of values in a column.
55. What is the purpose of the AVG() function?
a. The AVG() function is used to calculate the average value of a column.
56. What is the purpose of the MAX() function?
a. The MAX() function is used to retrieve the maximum value from a column.
57. What is the purpose of the MIN() function?
a. The MIN() function is used to retrieve the minimum value from a column.
58. What is the purpose of the GROUP_CONCAT() function?
a. The GROUP_CONCAT() function is used to concatenate values from multiple rows
into a single string, grouped by a specific column.
59. What is the purpose of the JOIN keyword?
a. The JOIN keyword is used to combine rows from two or more tables based on
related columns.
60. What is a self-referencing table?
a. A self-referencing table is a table that has a foreign key column referencing its
own primary key. It is used to represent hierarchical relationships within a single
table.
61. What is the difference between UNION and UNION ALL?
a. UNION combines the result sets of two or more SELECT statements and removes
duplicate rows, whereas UNION ALL combines the result sets without removing
duplicates.
62. What is the purpose of the ROW_NUMBER() function?
a. The ROW_NUMBER() function assigns a unique sequential number to each row
within a result set. It is often used for pagination or ranking purposes.
63. What is the purpose of the RANK() function?
a. The RANK() function assigns a rank to each row within a result set based on a
specified criteria, such as ordering by a column. It allows you to identify the
ranking of each row.
64. What is the purpose of the DENSE_RANK() function?
a. The DENSE_RANK() function is similar to the RANK() function but assigns
consecutive ranks to rows without gaps. If two rows have the same rank, the next
rank is skipped.
65. What is the purpose of the LAG() function?
a. The LAG() function is used to access the value of a previous row within a result set
based on a specified column. It allows you to compare values across adjacent
rows.
66. What is the purpose of the LEAD() function?
a. The LEAD() function is used to access the value of a subsequent row within a
result set based on a specified column. It allows you to compare values across
adjacent rows.
67. What is the purpose of the COALESCE() function?
a. The COALESCE() function is used to return the first non-null value from a list of
expressions. It is often used to provide a default value when a column value is null.
68. What is the purpose of the CASE statement?
a. The CASE statement is used to perform conditional logic within a SQL statement. It
allows you to evaluate multiple conditions and return different values based on
the result.
69. What is the purpose of the TRUNCATE TABLE statement?
a. The TRUNCATE TABLE statement is used to remove all rows from a table, while
keeping the table structure intact. It is faster than deleting all rows using the
DELETE statement.
70. What is the purpose of the CONSTRAINT keyword?
a. The CONSTRAINT keyword is used to define rules and relationships on columns
within a table. It ensures data integrity and enforces business rules.
71. What is the purpose of the PRIMARY KEY constraint?
a. The PRIMARY KEY constraint is used to uniquely identify each record in a table. It
ensures that the primary key column(s) have unique values and cannot contain
null values.
72. What is the purpose of the FOREIGN KEY constraint?
a. The FOREIGN KEY constraint is used to establish a relationship between two tables
based on a common column. It ensures referential integrity by enforcing that
values in the foreign key column exist in the referenced table's primary key.
73. What is the purpose of the INDEX keyword?
a. The INDEX keyword is used to create an index on one or more columns of a table. It
improves query performance by allowing faster data retrieval based on the
indexed columns.
74. What is the purpose of the CASCADE keyword in a FOREIGN KEY constraint?
a. The CASCADE keyword is used to specify that changes made to the primary key
values in the referenced table should be propagated to the foreign key values in
the referring table. This ensures that the relationship remains valid.
75. What is the purpose of the UPDATE statement?
a. The UPDATE statement is used to modify existing records in a table. It allows you to
change the values of one or more columns based on specified conditions.
76. What is the purpose of the DELETE statement?
a. The DELETE statement is used to remove one or more records from a table. It
allows you to delete rows based on specified conditions.
77. What is the purpose of the COMMIT statement?
a. The COMMIT statement is used to permanently save all changes made within a
transaction to the database. Once committed, the changes are visible to other
users.
78. What is the purpose of the ROLLBACK statement?
a. The ROLLBACK statement is used to undo all changes made within a transaction
and restore the database to its previous state. It is typically used when an error
occurs or when the transaction needs to be canceled.
79. What is the purpose of the SAVEPOINT statement?
a. The SAVEPOINT statement is used to define a specific point within a transaction to
which you can roll back. It allows you to undo changes up to a specific savepoint
without rolling back the entire transaction.
80. What is the purpose of the CONSTRAINT keyword in the ALTER TABLE statement?
a. The CONSTRAINT keyword in the ALTER TABLE statement is used to add, modify, or
drop constraints on columns within an existing table.
81. What is the purpose of the DISTINCT keyword in the SELECT statement?
a. The DISTINCT keyword in the SELECT statement is used to retrieve unique values
from a column in the result set, eliminating duplicate rows.
82. What is the purpose of the AS keyword in the SELECT statement?
a. The AS keyword in the SELECT statement is used to assign an alias to a column or
a table. It allows you to refer to the column or table by the assigned alias in
subsequent parts of the query.
83. What is the purpose of the ORDER BY clause in the SELECT statement?
a. The ORDER BY clause in the SELECT statement is used to sort the result set based
on one or more columns in ascending or descending order.
84. What is the purpose of the GROUP BY clause in the SELECT statement?
a. The GROUP BY clause in the SELECT statement is used to group rows based on one
or more columns. It is typically used with aggregate functions to perform
calculations on each group.
85. What is the purpose of the HAVING clause in the SELECT statement?
a. The HAVING clause in the SELECT statement is used to filter grouped rows based
on specific conditions. It operates on the results of the GROUP BY clause.
86. What is the purpose of the LIMIT clause in the SELECT statement?
a. The LIMIT clause in the SELECT statement is used to restrict the number of rows
returned by a query. It allows you to specify the maximum number of rows to be
retrieved.
87. What is the purpose of the OFFSET clause in the SELECT statement?
a. The OFFSET clause in the SELECT statement is used in conjunction with the LIMIT
clause to skip a specified number of rows before starting to return the result set.
88. What is the purpose of the JOIN keyword in the SELECT statement?
a. The JOIN keyword in the SELECT statement is used to combine rows from two or
more tables based on related columns. It allows you to retrieve data from multiple
tables in a single query.
89. What is the purpose of the INNER JOIN?
a. The INNER JOIN is a join operation that returns only the matching rows from both
tables based on the specified join condition. It combines rows that have matching
values in the joined columns.
90. What is the purpose of the LEFT JOIN?
a. The LEFT JOIN is a join operation that returns all rows from the left table and the
matching rows from the right table based on the specified join condition. If no
match is found, null values are returned for the right table columns.
91. What is the purpose of the RIGHT JOIN?
a. The RIGHT JOIN is a join operation that returns all rows from the right table and the
matching rows from the left table based on the specified join condition. If no
match is found, null values are returned for the left table columns.
92. What is the purpose of the FULL OUTER JOIN?
a. The FULL OUTER JOIN is a join operation that returns all rows from both tables,
including unmatched rows, and combines them based on the join condition. If no
match is found, null values are returned for the respective columns.
93. What is the purpose of the UNION operator?
a. The UNION operator is used to combine the result sets of two or more SELECT
statements into a single result set. It removes duplicate rows from the final result
set.
94. What is the purpose of the UNION ALL operator?
a. The UNION ALL operator is used to combine the result sets of two or more SELECT
statements into a single result set, including duplicate rows.
95. What is the purpose of the LIKE operator in the WHERE clause?
a. The LIKE operator is used in the WHERE clause to search for a specified pattern in a
column. It allows wildcard characters like % (matches any sequence of
characters) and _ (matches any single character).
96. What is the purpose of the IN operator in the WHERE clause?
a. The IN operator is used in the WHERE clause to check if a value matches any value
in a list or a subquery.
97. What is the purpose of the EXISTS operator in the WHERE clause?
a. The EXISTS operator is used in the WHERE clause to check if a subquery returns any
rows. It returns true if the subquery result set is not empty.
98. What is the purpose of the GROUP BY clause in the SELECT statement?
a. The GROUP BY clause in the SELECT statement is used to group rows based on one
or more columns. It is typically used with aggregate functions to perform
calculations on each group.
99. What is the purpose of the ORDER BY clause in the SELECT statement?
a. The ORDER BY clause in the SELECT statement is used to sort the result set based
on one or more columns in ascending or descending order.
100. What is the purpose of the DISTINCT keyword in the SELECT statement?
- The DISTINCT keyword in the SELECT statement is used to retrieve unique values
from a column in the result set, eliminating duplicate rows.
100 Most Asked
JavaScript Interview
QnA
Made By:
1. What is JavaScript?
JavaScript is a high-level, interpreted programming language primarily used for
adding interactivity to web pages.
2. What are the data types in JavaScript?
JavaScript has six primitive data types: string, number, boolean, null, undefined, and
symbol, along with a complex data type called object.
3. What is the difference between null and undefined?
null represents the intentional absence of any object value, while undefined indicates
the absence of a value or an uninitialized variable.
4. What is the DOM in JavaScript?
The Document Object Model (DOM) is a programming interface that represents the
structure of HTML and XML documents. It allows JavaScript to access and manipulate
the content and structure of a webpage.
5. What is an event in JavaScript?
An event is an action or occurrence that happens in the browser, such as a button
click or page load. JavaScript can respond to these events by executing code in
response.
6. What is an anonymous function in JavaScript?
An anonymous function is a function without a name. It can be assigned to a
variable or passed as an argument to another function. They are often used for one-
time or callback functions.
7. What are closures in JavaScript?
Closures are functions that have access to variables from an outer function, even
after the outer function has finished executing. They encapsulate data and provide a
way to maintain state between function calls.
8. What is the difference between == and === in JavaScript?
The == operator checks for equality after performing type coercion, while the ===
operator checks for equality without type coercion, ensuring both the value and type
match.
9. 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 the compilation phase, allowing
them to be used before they are declared.
10. What is the this keyword in JavaScript?
The this keyword refers to the object that is currently executing the code. Its value is
determined by how a function is called, and it provides a way to access object
properties and methods within a function.
11. What are the different ways to define a function in JavaScript?
Functions in JavaScript can be defined using function declarations, function
expressions, arrow functions, and methods within objects.
12. What is the purpose of the let keyword in JavaScript?
The let keyword is used to declare block-scoped variables in JavaScript. Variables
declared with let are only accessible within the block where they are defined.
13. What is the purpose of the const keyword in JavaScript?
The const keyword is used to declare block-scoped variables in JavaScript that
cannot be re-assigned. However, it does not make objects or arrays immutable.
14. What are template literals in JavaScript?
Template literals, denoted by backticks (`), are a way to create strings in JavaScript
that support interpolation of variables and multi-line strings.
15. What are JavaScript promises?
Promises are used for asynchronous programming in JavaScript. They represent the
eventual completion (or failure) of an asynchronous operation and allow chaining of
operations using .then() and .catch().
16. What is the async/await syntax in JavaScript?
The async/await syntax is a modern approach to handle asynchronous operations. It
allows writing asynchronous code in a more synchronous-like manner, making it
easier to read and maintain.
17. What are arrow functions in JavaScript?
Arrow functions are a concise syntax for defining functions in JavaScript. They have a
shorter syntax compared to traditional function expressions and inherit the this value
from the enclosing scope.
18. What is event delegation in JavaScript?
Event delegation is a technique where you attach an event listener to a parent
element instead of individual child elements. It allows handling events efficiently,
especially for dynamically added elements.
19. What is the purpose of the map() function in JavaScript?
The map() function is used to create a new array by applying a given function to
each element of an existing array. It allows transforming and manipulating array
elements easily.
20. What is the purpose of the filter() function in JavaScript?
The filter() function is used to create a new array containing elements that pass a
certain condition defined by a provided function. It allows filtering elements from an
array based on specific criteria.
21. What is the purpose of the reduce() function in JavaScript?
The reduce() function is used to reduce an array to a single value by applying a
function to each element and accumulating the result. It is often used to perform
calculations or transformations on arrays.
22. What is a callback function in JavaScript?
A callback function is a function that is passed as an argument to another function
and gets executed at a later time or in response to an event. It enables asynchronous
and event-driven programming.
23. What is the difference between let and var in JavaScript?
The let keyword declares block-scoped variables, while the var keyword declares
function-scoped variables. Variables declared with var are hoisted, while variables
declared with let are not.
24. What are JavaScript modules?
JavaScript modules are reusable pieces of code that encapsulate related
functionality. They allow for better organization, encapsulation, and code reuse in
larger JavaScript applications.
25. What is object destructuring in JavaScript?
Object destructuring is a feature that allows extracting properties from objects and
assigning them to variables. It provides a concise way to extract values and work
with object properties.
26. What are JavaScript classes?
JavaScript classes are a way to define objects with shared properties and behaviors.
They provide a template for creating multiple instances of objects with similar
characteristics.
27. What is inheritance in JavaScript?
Inheritance is a mechanism in JavaScript where an object can inherit properties and
methods from another object. It allows for code reuse and creating hierarchical
relationships between objects.
28. What are JavaScript getters and setters?
Getters and setters are special methods used to get and set the values of object
properties, respectively. They provide control over property access and enable data
validation and encapsulation.
29. What is the purpose of the try/catch statement in JavaScript?
The try/catch statement is used for error handling in JavaScript. It allows catching
and handling exceptions that occur during the execution of a block of code.
30. What is the difference between let and const in JavaScript?
The let keyword is used to declare variables that can be reassigned, while the const
keyword is used to declare variables that are read-only and cannot be reassigned.
31. What is the purpose of the forEach() function in JavaScript?
The forEach() function is used to execute a provided function once for each element
in an array. It provides an easy way to iterate over array elements and perform
operations on them.
32. What is the purpose of the localStorage object in JavaScript?
The localStorage object allows web applications to store key-value pairs locally
within the user's browser. It provides a simple way to store and retrieve data
persistently.
33. What are arrow functions? How are they different from regular functions?
Arrow functions are a concise syntax for defining functions in JavaScript. They have a
shorter syntax compared to regular functions and do not bind their own this value.
34. What is the purpose of the setTimeout() function in JavaScript?
The setTimeout() function is used to schedule the execution of a function after a
specified delay in milliseconds. It allows adding time-based delays to JavaScript
code.
35. What is event bubbling in JavaScript?
Event bubbling is a mechanism in which an event triggered on a specific element will
also trigger the same event on all of its parent elements. It starts from the innermost
element and propagates upwards in the DOM tree.
36. What is the purpose of the fetch() function in JavaScript?
The fetch() function is used to make HTTP requests and fetch resources from the
network. It provides a modern and flexible way to perform asynchronous network
requests.
37. What is the difference between null and undefined?
null is an explicitly assigned value that represents the absence of an object, while
undefined is a value assigned by the JavaScript engine to variables that have been
declared but have not been assigned a value.
38. What is event propagation in JavaScript?
Event propagation is the process of an event being triggered on an element and then
propagating to its parent elements or capturing down from its parent elements. It
allows handling events at different levels of the DOM hierarchy.
39. What is the purpose of the Object.keys() function in JavaScript?
The Object.keys() function is used to extract all the keys of an object and return them
as an array. It provides an easy way to iterate over an object's properties.
40. What is the difference between null and undefined in JavaScript?
null is an assigned value that represents the intentional absence of an object value,
while undefined represents an uninitialized or undefined value, often used as a
default initial value.
41. What is the purpose of the addEventListener() method in JavaScript?
The addEventListener() method is used to attach an event listener to an element. It
allows you to listen for specific events and execute a function when the event is
triggered.
42. What is the purpose of the parentNode property in JavaScript?
The parentNode property is used to access the parent node of an element in the
DOM. It allows traversal and manipulation of the DOM tree by accessing the
immediate parent of an element.
43. What is the purpose of the querySelector() method in JavaScript?
The querySelector() method is used to select the first element that matches a
specified CSS selector. It provides a powerful way to retrieve elements from the DOM
based on CSS selectors.
44. What is the purpose of the querySelectorAll() method in JavaScript?
The querySelectorAll() method is used to select all elements that match a specified
CSS selector. It returns a collection of elements that can be iterated over or accessed
using indexing.
45. What is the difference between querySelector() and getElementById()?
querySelector() is a more versatile method that allows selecting elements based on
any CSS selector, while getElementById() is specifically used to select an element by
its unique id attribute.
46. What is the difference between function declarations and function expressions in
JavaScript?
Function declarations are hoisted and can be called before they are defined, while
function expressions are not hoisted and must be defined before they are called.
47. What is the purpose of the bind() method in JavaScript?
The bind() method is used to create a new function with a specified this value and
initial arguments. It allows explicit binding of the this value within a function.
48. What is the purpose of the call() method in JavaScript?
The call() method is used to invoke a function with a specified this value and
arguments provided individually. It allows borrowing methods from other objects
and explicit invocation of functions.
49. What is the purpose of the apply() method in JavaScript?
The apply() method is used to invoke a function with a specified this value and
arguments provided as an array or an array-like object. It allows borrowing methods
from other objects and explicit invocation of functions.
50. What is the purpose of the Array.isArray() method in JavaScript?
The Array.isArray() method is used to determine whether a given value is an array or
not. It returns true if the value is an array, and false otherwise.
51. What is event capturing in JavaScript?
Event capturing is the process of an event being triggered on an element's parent
elements first, before reaching the target element. It allows capturing events at the
outermost level of the DOM hierarchy.
52. What is event delegation in JavaScript?
Event delegation is a technique where you attach an event listener to a parent
element instead of individual child elements. It allows handling events efficiently,
especially for dynamically added elements.
53. What is the purpose of the startsWith() method in JavaScript?
The startsWith() method is used to check if a string starts with a specified substring.
It returns true if the string starts with the substring, and false otherwise.
54. What is the purpose of the endsWith() method in JavaScript?
The endsWith() method is used to check if a string ends with a specified substring. It
returns true if the string ends with the substring, and false otherwise.
55. What is the purpose of the includes() method in JavaScript?
The includes() method is used to check if a string contains a specified substring. It
returns true if the substring is found, and false otherwise.
56. What is the purpose of the padStart() method in JavaScript?
The padStart() method is used to pad the beginning of a string with a specified
character until it reaches a desired length. It is often used for formatting purposes.
57. What is the purpose of the padEnd() method in JavaScript?
The padEnd() method is used to pad the end of a string with a specified character
until it reaches a desired length. It is often used for formatting purposes.
58. What is the purpose of the charAt() method in JavaScript?
The charAt() method is used to retrieve the character at a specified index in a string.
It returns the character at the specified index or an empty string if the index is out of
range.
59. What is the purpose of the charCodeAt() method in JavaScript?
The charCodeAt() method is used to retrieve the Unicode value of the character at a
specified index in a string. It returns the Unicode value of the character or NaN if the
index is out of range.
60. What is the purpose of the String.fromCharCode() method in JavaScript?
The String.fromCharCode() method is used to create a string from a sequence of
Unicode values. It allows converting Unicode values to their corresponding
characters.
61. What is the purpose of the JSON.stringify() method in JavaScript?
The JSON.stringify() method is used to convert a JavaScript object or value to a JSON
string. It is commonly used for data serialization and communication with web
servers.
62. What is the purpose of the JSON.parse() method in JavaScript?
The JSON.parse() method is used to parse a JSON string and convert it into a
JavaScript object or value. It is commonly used to deserialize JSON data received
from a server.
63. What is the purpose of the encodeURIComponent() function in JavaScript?
The encodeURIComponent() function is used to encode special characters in a URL
component. It ensures that the component can be included in a URL without causing
any parsing errors.
64. What is the purpose of the decodeURIComponent() function in JavaScript?
The decodeURIComponent() function is used to decode URL-encoded components.
It converts URL-encoded characters back to their original form.
65. What is the purpose of the Math.random() function in JavaScript?
The Math.random() function is used to generate a random floating-point number
between 0 (inclusive) and 1 (exclusive). It is often used to introduce randomness in
JavaScript programs.
66. What is the purpose of the Math.floor() function in JavaScript?
The Math.floor() function is used to round a number down to the nearest integer. It
removes the decimal part of the number and returns the largest integer less than or
equal to the given number.
67. What is the purpose of the Math.ceil() function in JavaScript?
The Math.ceil() function is used to round a number up to the nearest integer. It
increases the number to the next higher integer, regardless of the decimal part.
68. What is the purpose of the Math.round() function in JavaScript?
The Math.round() function is used to round a number to the nearest integer. It rounds
the number up or down based on the decimal part.
69. What is the purpose of the Math.max() function in JavaScript?
The Math.max() function is used to find the largest number among a list of
arguments. It returns the highest value passed as an argument.
70. What is the purpose of the Math.min() function in JavaScript?
The Math.min() function is used to find the smallest number among a list of
arguments. It returns the lowest value passed as an argument.
71. What is the purpose of the Math.pow() function in JavaScript?
The Math.pow() function is used to calculate the power of a number. It takes a base
and an exponent as arguments and returns the result of raising the base to the
exponent.
72. What is the purpose of the Math.sqrt() function in JavaScript?
The Math.sqrt() function is used to calculate the square root of a number. It returns
the positive square root of the given number.
73. What is the purpose of the Math.abs() function in JavaScript?
The Math.abs() function is used to calculate the absolute value of a number. It
returns the magnitude of the number without considering its sign.
74. What is the purpose of the Math.floor() and Math.random() functions together?
By combining Math.floor() and Math.random() functions, you can generate a
random integer within a specified range. For example, Math.floor(Math.random() *
10) generates a random integer between 0 and 9.
75. What is the purpose of the Date() constructor in JavaScript?
The Date() constructor is used to create a new JavaScript Date object that
represents a specific date and time. It allows working with dates and performing
various operations on them.
76. What is the purpose of the getFullYear() method in JavaScript Date objects?
The getFullYear() method is used to retrieve the four-digit year value of a JavaScript
Date object. It returns the year as a four-digit number, such as 2023.
77. What is the purpose of the getMonth() method in JavaScript Date objects?
The getMonth() method is used to retrieve the month value of a JavaScript Date
object. It returns a zero-based index, where January is represented by 0 and
December by 11.
78. What is the purpose of the getDate() method in JavaScript Date objects?
The getDate() method is used to retrieve the day of the month value of a JavaScript
Date object. It returns the day as a number between 1 and 31.
79. What is the purpose of the getDay() method in JavaScript Date objects?
The getDay() method is used to retrieve the day of the week value of a JavaScript
Date object. It returns a zero-based index, where Sunday is represented by 0 and
Saturday by 6.
80. What is the purpose of the getHours() method in JavaScript Date objects?
The getHours() method is used to retrieve the hour value of a JavaScript Date object.
It returns the hour as a number between 0 and 23.
81. What is the purpose of the getMinutes() method in JavaScript Date objects?
The getMinutes() method is used to retrieve the minute value of a JavaScript Date
object. It returns the minute as a number between 0 and 59.
82. What is the purpose of the getSeconds() method in JavaScript Date objects?
The getSeconds() method is used to retrieve the second value of a JavaScript Date
object. It returns the second as a number between 0 and 59.
83. What is the purpose of the getFullYear() and getMonth() methods together in
JavaScript Date objects?
By combining the getFullYear() and getMonth() methods, you can retrieve the full
date in a human-readable format. For example, const currentDate = new Date();
const year = currentDate.getFullYear(); const month = currentDate.getMonth();
console.log(year + '-' + (month + 1)); will print the current year and month in the
format 'YYYY-MM'.
84. What is the purpose of the setFullYear() method in JavaScript Date objects?
The setFullYear() method is used to set the year value of a JavaScript Date object. It
allows modifying the year component of a date.
85. What is the purpose of the setMonth() method in JavaScript Date objects?
The setMonth() method is used to set the month value of a JavaScript Date object. It
allows modifying the month component of a date.
86. What is the purpose of the setDate() method in JavaScript Date objects?
The setDate() method is used to set the day of the month value of a JavaScript Date
object. It allows modifying the day component of a date.
87. What is the purpose of the setHours() method in JavaScript Date objects?
The setHours() method is used to set the hour value of a JavaScript Date object. It
allows modifying the hour component of a date.
88. What is the purpose of the setMinutes() method in JavaScript Date objects?
The setMinutes() method is used to set the minute value of a JavaScript Date object.
It allows modifying the minute component of a date.
89. What is the purpose of the setSeconds() method in JavaScript Date objects?
The setSeconds() method is used to set the second value of a JavaScript Date
object. It allows modifying the second component of a date.
90. What is the purpose of the toLocaleString() method in JavaScript Date objects?
The toLocaleString() method is used to convert a JavaScript Date object to a
localized string representation based on the current locale. It considers the user's
time zone and regional settings to format the date and time.
91. What is the purpose of the toDateString() method in JavaScript Date objects?
The toDateString() method is used to convert the date portion of a JavaScript Date
object to a human-readable string representation. It returns the date in the format
'Day Mon DD YYYY', such as 'Thu Jun 24 2023'.
92. What is the purpose of the getTime() method in JavaScript Date objects?
The getTime() method is used to retrieve the timestamp value of a JavaScript Date
object. It returns the number of milliseconds elapsed since January 1, 1970, 00:00:00
UTC.
93. What is the purpose of the setTime() method in JavaScript Date objects?
The setTime() method is used to set the timestamp value of a JavaScript Date
object. It allows modifying the date and time by providing a new timestamp.
94. What is the purpose of the setTimeout() function in JavaScript?
The setTimeout() function is used to execute a specified function or a piece of code
after a delay specified in milliseconds. It is commonly used for delaying the
execution of code or creating timeouts.
95. What is the purpose of the setInterval() function in JavaScript?
The setInterval() function is used to repeatedly execute a specified function or a
piece of code at a fixed interval specified in milliseconds. It is commonly used for
creating intervals and timers.
96. What is the purpose of the clearTimeout() function in JavaScript?
The clearTimeout() function is used to cancel a timeout set by the setTimeout()
function. It clears the scheduled execution of a function before it is triggered.
97. What is the purpose of the clearInterval() function in JavaScript?
The clearInterval() function is used to cancel an interval set by the setInterval()
function. It stops the repeated execution of a function at a fixed interval.
98. What is the purpose of the isNaN() function in JavaScript?
The isNaN() function is used to check if a value is NaN (Not-a-Number). It returns
true if the value is NaN, and false otherwise.
99. What is the purpose of the isFinite() function in JavaScript?
The isFinite() function is used to check if a value is a finite number. It returns true if
the value is a finite number, and false otherwise. It also returns false for NaN, Infinity,
and -Infinity.
100. What is the purpose of the parseFloat() function in JavaScript?
The parseFloat() function is used to parse a string and extract a floating-point
number from it. It converts the initial portion of the string that represents a valid
floating-point number into a number value.