HTML_Interview_Questions - Copy (2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

HTML Interview Questions and Answers

Basic HTML Questions (Easy)

What is HTML?
HTML stands for HyperText Markup Language. It is the standard language used to create
web pages and web applications.

What are HTML tags? Can you name a few?


HTML tags are the building blocks of HTML that define the structure and content of a
webpage. Examples include <p>, <h1>, <a>, <div>, etc.

What is the difference between block-level and inline elements?


Block-level elements (e.g., <div>, <h1>) take up the full width of their parent container,
whereas inline elements (e.g., <span>, <a>) take only as much space as necessary.

What is the <DOCTYPE> declaration?


The <!DOCTYPE> declaration is used to define the version of HTML used in the document. It
must be the very first line of code in an HTML document.

What is the purpose of the <head> tag in HTML?


The <head> tag contains meta-information about the document, such as its title (<title>),
character set, external resources (stylesheets, scripts), and meta tags (description,
keywords).

Intermediate HTML Questions (Medium)

What is the difference between HTML and XHTML?


HTML is more lenient with syntax, whereas XHTML is a stricter version of HTML, enforcing
XML rules such as proper closing of all tags and case sensitivity.

What are semantic HTML tags, and why should you use them?
Semantic HTML tags (like <article>, <footer>, <section>, etc.) clearly describe the meaning
and purpose of the content inside them, which improves accessibility and SEO.

Explain the difference between <section>, <div>, and <article>.


<div> is a generic container, whereas <section> is used to group related content, and
<article> is used for self-contained content, like a blog post.
What is the purpose of the <meta> tag in HTML?
The <meta> tag provides metadata about the HTML document, such as the character
encoding, viewport settings for responsive design, and SEO-related information
(description, keywords).

What are the differences between <link>, <script>, and <style> tags?
<link>: Links external resources like CSS files.
<script>: Embeds or references JavaScript files.
<style>: Embeds internal CSS styles directly into an HTML document.

Advanced HTML Questions (Hard)

How does the browser render HTML, and what happens from when you type a
URL until the page loads?
When a URL is entered, the browser sends an HTTP request to the server. The server
responds with HTML, CSS, and JavaScript files, which the browser parses to build the DOM
(Document Object Model) and render the page.

What is the difference between id and class attributes?


id: Unique identifier for an element, meant to be used once per page.
class: Can be used multiple times to group elements with similar styling or behavior.

What are the different types of HTML form elements, and how do they work?
Form elements include <input>, <textarea>, <select>, <button>, etc., which allow users to
enter and submit data to the server. Each has attributes like type, name, and value to
manage data.

What are data attributes, and how are they used in HTML?
Data attributes allow you to embed custom data within HTML elements using the data-
prefix, which can later be accessed via JavaScript.

How do you ensure accessibility in HTML?


To ensure accessibility, use semantic tags, provide proper alt text for images, add aria-
attributes for dynamic content, use headings correctly, and ensure the site is navigable via
keyboard.

Responsive Design & Performance Questions

How do you make an HTML page responsive?


Responsive design can be achieved by using the <meta viewport> tag, media queries in CSS,
flexible grids, and relative units like %, em, and rem.
What is lazy loading in HTML, and how is it implemented?
Lazy loading is a technique to delay the loading of non-critical resources (e.g., images,
videos) until they are needed. This can be done by using the loading="lazy" attribute on
images.

What is the purpose of the <picture> tag?


The <picture> tag allows you to define multiple sources for an image, making it useful for
responsive images by loading different image files based on screen size, resolution, or
format support.

Explain how to improve the performance of HTML pages.


To improve performance, you can:
- Minimize HTML, CSS, and JavaScript files.
- Optimize images by using formats like WebP.
- Enable browser caching.
- Use async/defer attributes for scripts to load them non-blocking.

What are web components, and how do they work?


Web components are a set of APIs that allow developers to create custom, reusable HTML
elements. They consist of Shadow DOM, custom elements, and HTML templates.

CSS Interview Questions and Answers


Basic CSS Questions (Easy)

What is CSS?
CSS (Cascading Style Sheets) is a language used to style the appearance of HTML elements
on a web page. It controls layout, color, fonts, and more.

What is the difference between class and id selectors in CSS?


A class selector can be used on multiple elements, while an id is unique to one element. You
use `.` to select a class (e.g., `.example`) and `#` to select an id (e.g., `#example`).

What are the three ways to apply CSS to a web page?


Inline CSS (using the `style` attribute inside an HTML element), Internal CSS (using a
`<style>` tag in the `<head>` section), and External CSS (linking a separate `.css` file using
the `<link>` tag).
What is the purpose of the box-sizing property in CSS?
The `box-sizing` property controls how the width and height of an element are calculated,
including padding and borders. Common values are `content-box` and `border-box`.

What are pseudo-classes in CSS?


Pseudo-classes (like `:hover`, `:focus`, `:nth-child`) allow you to style elements based on
their state or position within the DOM.

Intermediate CSS Questions (Medium)

Explain the CSS Box Model.


The CSS Box Model consists of four areas: content, padding, border, and margin. It defines
how an element is rendered in terms of space it occupies on a page.

How does Flexbox work in CSS?


Flexbox is a layout model that allows you to design a flexible and responsive layout
structure without using floats or positioning. Flex items adjust and align according to the
container’s properties (`display: flex`, `justify-content`, `align-items`, etc.).

What is the difference between position: absolute, relative, fixed, and sticky?
absolute: Positioned relative to the nearest positioned ancestor. relative: Positioned relative
to its normal position. fixed: Positioned relative to the viewport. sticky: Switches between
relative and fixed positioning based on the scroll position.

What is the z-index property in CSS?


The `z-index` property controls the vertical stacking order of elements. Elements with a
higher `z-index` appear on top of elements with a lower `z-index`.

How can you create a responsive design using CSS?


Responsive design can be achieved using media queries, flexible grids, percentages for
layout, and responsive units like `em` or `rem`. Flexbox and CSS Grid are commonly used for
responsive layouts.

Advanced CSS Questions (Hard)

What are CSS preprocessors, and how do they differ from CSS?
CSS preprocessors like SASS, LESS, and Stylus extend CSS with features like variables,
nested rules, and functions. They require compilation into standard CSS.

What is the difference between display: none and visibility: hidden in CSS?
display: none removes the element from the document flow, while visibility: hidden hides
the element but maintains its space in the layout.
Explain CSS Grid and how it differs from Flexbox.
CSS Grid is a two-dimensional layout system, meaning you can control both rows and
columns. Flexbox is a one-dimensional layout system (either row or column). CSS Grid is
more suited for complex layouts, while Flexbox is ideal for simpler, one-axis alignment.

How do CSS animations work, and what are keyframes?


CSS animations use `@keyframes` to define the intermediate steps between start and end
states of an animation. You can apply the animation to elements using the `animation`
property.

How can you optimize CSS for better performance?


Optimizing CSS can involve minimizing the size of CSS files (e.g., through minification),
reducing the use of complex selectors, deferring non-critical CSS, and limiting the number of
style recalculations.

Responsive Design & Performance Questions

How does the min-width and max-width properties help in responsive design?
min-width sets a minimum width for an element, ensuring it doesn’t shrink below a certain
size, while max-width limits how wide an element can grow. Both help in creating layouts
that adapt to various screen sizes.

What is the difference between rem and em units in CSS?


rem is relative to the root element’s font size, while em is relative to the font size of its
parent element. rem provides more consistency in sizing across elements.

What is the difference between transform: translate() and position: relative?


transform: translate() moves an element visually but does not affect the document flow or
neighboring elements, whereas position: relative shifts the element while keeping it in the
flow.

How can you create a CSS-only dropdown menu?


A CSS-only dropdown can be created using the `:hover` pseudo-class to display a submenu
when the user hovers over a parent menu item.

Explain what critical CSS is.


Critical CSS refers to the minimum amount of CSS required to render the visible portion of
the page. It helps to improve the page's loading time by deferring non-essential CSS until the
critical content has been rendered.
JS Interview Questions and Answers
Beginner Level:

1. What are the different data types in JavaScript?


Answer: JavaScript supports the following data types: string, number, boolean, null,
undefined, object, and symbol (introduced in ES6).

2. What is the difference between `let`, `var`, and `const`?


- Answer: `var` is function-scoped, whereas `let` and `const` are block-scoped. `const`
variables cannot be reassigned, while `let` variables can.

3. What is a closure in JavaScript?


- Answer: A closure is a function that remembers its lexical scope even when the function
is executed outside that scope. For example, a function inside another function has access to
the outer function's variables.

4. What is `this` in JavaScript?


- Answer: `this` refers to the object that is currently executing the code. In a method, `this`
refers to the owner object, while in a regular function, it refers to the global object or
`undefined` in strict mode.

5. What are arrow functions?


- Answer: Arrow functions are a concise way to define functions in ES6. They do not bind
their own `this`, which means they inherit the value of `this` from the surrounding lexical
context.

Intermediate Level:

1. What is the event loop in JavaScript?


- Answer: The event loop is a mechanism that handles asynchronous operations. It checks
the call stack and the task queue. When the call stack is empty, the event loop picks the next
function from the task queue to execute.

2. What are promises in JavaScript?


- Answer: A promise is an object representing the eventual completion or failure of an
asynchronous operation. Promises have three states: pending, fulfilled, and rejected.

3. What is the difference between `==` and `===`?


- Answer: `==` performs type coercion before comparing, meaning different types can be
considered equal. `===` is a strict equality operator, which compares both value and type
without coercion.
4. What is the purpose of `bind()`, `call()`, and `apply()` in JavaScript?
- Answer: These methods are used to set the value of `this` inside a function. `bind()`
creates a new function with the specified `this`, while `call()` and `apply()` execute the
function with a given `this` value, with `apply()` accepting arguments as an array.

5. What is hoisting in JavaScript?


- Answer: Hoisting is a behavior in JavaScript where variable and function declarations are
moved to the top of their containing scope before code execution. Only declarations are
hoisted, not initializations.

Advanced Level:

1. What is the difference between `null` and `undefined`?

- Answer: `null` is an assignment value that represents the intentional absence of a value,
whereas `undefined` means a variable has been declared but not yet assigned a value.

2. Explain JavaScript's prototype-based inheritance.

- Answer: In JavaScript, objects can inherit properties and methods from other objects.
This is achieved through prototypes, where every object has a prototype from which it can
inherit properties. Prototypal inheritance allows an object to use properties and methods
defined in its prototype.

3. What are higher-order functions in JavaScript?

- Answer: Higher-order functions are functions that can take other functions as arguments
or return them as results. Examples include `map()`, `filter()`, and `reduce()`.

4. What are modules in JavaScript, and how do you use them?

- Answer: Modules are reusable pieces of code that can be exported from one file and
imported into another. JavaScript ES6 introduced `import` and `export` for managing
modules, allowing for better separation of code.

5. What is `async`/`await` and how does it differ from promises?


- Answer: `async`/`await` is syntactic sugar built on top of promises that allows writing
asynchronous code in a more synchronous fashion. `async` functions return a promise, and
`await` is used to pause the execution of code until the promise is resolved or rejected.

6. Explain event delegation in JavaScript.

- Answer: Event delegation is a technique where a single event listener is added to a


parent element to manage events on its child elements. This improves performance and
allows for handling dynamic content by using event bubbling.

7. What is debouncing and throttling in JavaScript?

- Answer: Debouncing ensures that a function is called only once after a specified time
period of inactivity, whereas throttling limits the number of times a function is called in a
given time frame.

8. What is the `new` keyword in JavaScript?

- Answer: The `new` keyword is used to create instances of user-defined objects or built-in
objects like `Date`. It sets the prototype of the instance to the constructor's prototype,
executes the constructor, and returns the new object.

9. What is the difference between deep and shallow copies in JavaScript?

- Answer: A shallow copy only copies references to objects, meaning changes to the copied
object reflect in the original. A deep copy duplicates the entire object structure, ensuring
that changes to the copy do not affect the original.

10. What are generators in JavaScript, and how are they different from regular functions?

- Answer: Generators are functions that can pause execution and resume later using the
`yield` keyword. They are useful for implementing iterators and lazy evaluation, unlike
regular functions that run to completion.
React Interview Questions and
Answers
### **Beginner Level:**

1. **What is React?**

- Answer: React is a JavaScript library for building user interfaces. It allows developers to
create reusable UI components and efficiently update the UI when data changes.

2. **What is JSX?**

- Answer: JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you
to write HTML-like code inside JavaScript and is compiled into regular JavaScript by tools
like Babel.

3. **What are props in React?**

- Answer: Props (short for properties) are used to pass data from a parent component to a
child component in React. They are read-only and help make components reusable.

4. **What is the difference between a functional component and a class component in


React?**

- Answer: Functional components are stateless and defined as JavaScript functions. Class
components can hold and manage state and lifecycle methods. Since the introduction of
hooks, functional components can also use state and lifecycle features.

5. **What is the purpose of the `key` prop in React?**

- Answer: The `key` prop is used to uniquely identify elements in an array or list. It helps
React to track which items have changed, added, or removed and efficiently update the
DOM.
### **Intermediate Level:**

1. **What is the virtual DOM, and how does it work?**

- Answer: The virtual DOM is a lightweight, in-memory representation of the actual DOM.
When a component's state or props change, React updates the virtual DOM first and then
compares it to the actual DOM. Only the changed parts of the DOM are updated (reconciled),
which makes updates faster.

2. **What are hooks in React, and why were they introduced?**

- Answer: Hooks are functions introduced in React 16.8 that allow you to use state and
other React features in functional components. They were introduced to simplify code
reuse, eliminate the need for class components in most cases, and manage side effects more
effectively.

3. **What is the `useState` hook, and how is it used?**

- Answer: The `useState` hook is used to manage state in a functional component. It


returns an array with two values: the current state and a function to update it. Example:

```jsx

const [count, setCount] = useState(0);

```

4. **What is the difference between controlled and uncontrolled components in React?**

- Answer: A controlled component is one where form data is handled by the React
component's state, while an uncontrolled component stores its data in the DOM. Controlled
components are typically preferred for better control over form data.

5. **What is the `useEffect` hook used for?**

- Answer: The `useEffect` hook allows you to perform side effects in functional
components, such as data fetching, subscriptions, or manually changing the DOM. It runs
after the render is committed to the screen.
### **Advanced Level:**

1. **What is the Context API in React?**

- Answer: The Context API allows you to pass data through the component tree without
having to manually pass props at every level. It is often used for global state management or
sharing data like themes, user authentication, etc.

2. **What is the difference between `useEffect` and `useLayoutEffect`?**

- Answer: `useEffect` runs asynchronously after the DOM has been painted, while
`useLayoutEffect` runs synchronously after React has calculated the DOM updates but
before the browser has painted. `useLayoutEffect` is useful when you need to perform a
DOM mutation and prevent layout jumps.

3. **What are higher-order components (HOCs) in React?**

- Answer: HOCs are functions that take a component and return a new component with
added behavior or functionality. They are used for reusing component logic. Example: a
HOC could add authentication to multiple components.

4. **What are React Portals?**

- Answer: React Portals allow you to render a child component into a DOM node outside of
its parent component’s DOM hierarchy. This is useful for scenarios like modals or tooltips
where you want to render outside the root element.

5. **What is server-side rendering (SSR) in React, and how does it differ from client-side
rendering (CSR)?**

- Answer: SSR is the process of rendering a React application on the server and sending
the fully rendered page to the client. It improves performance, SEO, and initial page load
times. CSR renders the React application on the client side, after the initial HTML file is
loaded.

6. **What is the difference between React.memo and useMemo?**


- Answer: `React.memo` is a higher-order component that memoizes a functional
component, preventing unnecessary re-renders. `useMemo` is a hook that memoizes a
calculation or value within a component, so it doesn’t recompute on every render unless its
dependencies change.

7. **What is reconciliation in React?**

- Answer: Reconciliation is the process React uses to update the DOM by comparing the
newly created virtual DOM with the previous one. React only updates the parts of the DOM
that have changed.

8. **What are fragments in React?**

- Answer: Fragments allow you to group multiple elements without adding extra nodes to
the DOM. Instead of wrapping elements in a `<div>`, you can use `<React.Fragment>` or
shorthand `<>`.

9. **What is React's `useReducer` hook, and how is it different from `useState`?**

- Answer: `useReducer` is an alternative to `useState` for more complex state logic. It is


often used when state changes depend on the previous state or when you want to centralize
state management. `useReducer` works similarly to a reducer function in Redux.

10. **What is lazy loading in React, and how do you implement it?**

- Answer: Lazy loading is a technique to defer the loading of components or resources


until they are needed. In React, you can implement lazy loading using `React.lazy()` for
dynamically importing components and `Suspense` for showing fallback content during
loading.
Expressjs/NodeJS Interview
Questions and Answers
### **Beginner Level:**

1. **What is Node.js?**

- Answer: Node.js is a runtime environment built on Chrome's V8 JavaScript engine that


allows you to run JavaScript on the server-side. It is commonly used for building scalable
network applications.

2. **What is NPM, and what is its purpose?**

- Answer: NPM (Node Package Manager) is a package manager for Node.js that helps
install, update, and manage project dependencies. It also allows you to share code modules
with the wider community.

3. **What is the difference between `require()` and `import` in Node.js?**

- Answer: `require()` is used in CommonJS modules, which is the default module system in
Node.js. `import` is used in ES6 modules, which is a newer standard and requires a specific
configuration in Node.js to enable.

4. **What is Express.js?**

- Answer: Express.js is a lightweight and flexible web application framework for Node.js
that simplifies the process of building web servers and APIs by providing features like
routing and middleware.

5. **What are middleware functions in Express.js?**

- Answer: Middleware functions are functions that have access to the request and
response objects and can modify them or end the response cycle. They can be used for tasks
like authentication, logging, and handling errors.
### **Intermediate Level:**

1. **What is event-driven programming in Node.js?**

- Answer: Event-driven programming is a paradigm where the flow of the program is


determined by events, such as user actions, messages from other programs, or sensor
outputs. Node.js uses an event loop to handle asynchronous operations, which makes it
highly scalable.

2. **Explain the role of the event loop in Node.js.**

- Answer: The event loop in Node.js is responsible for handling non-blocking,


asynchronous tasks. It listens for events, and when an operation completes, it executes the
appropriate callback function to continue the execution.

3. **What is `package.json` in Node.js?**

- Answer: `package.json` is a file that contains metadata about your Node.js project,
including project dependencies, scripts for running tasks, and information about the project
itself (e.g., version, author).

4. **How do you handle file uploads in Express?**

- Answer: You can handle file uploads in Express by using middleware like `multer`. It
allows you to handle `multipart/form-data`, which is used for uploading files in forms.

5. **What is the difference between blocking and non-blocking code in Node.js?**

- Answer: Blocking code waits for an operation to complete before moving to the next task,
whereas non-blocking code allows the program to continue running other tasks while the
operation completes in the background.

### **Advanced Level:**


1. **What is cluster mode in Node.js, and why is it used?**

- Answer: Cluster mode allows Node.js to take advantage of multi-core systems by


spawning multiple instances of the application, each running on a different core. This
improves the performance of applications that handle many requests simultaneously.

2. **What are streams in Node.js, and what are their types?**

- Answer: Streams are objects that allow you to read or write data in chunks, rather than
all at once, which makes them efficient for handling large files. The four types of streams
are: readable, writable, duplex (both readable and writable), and transform (a type of
duplex stream where the output is computed based on the input).

3. **What is the purpose of the `next()` function in Express?**

- Answer: The `next()` function in Express is used to pass control to the next middleware
function in the stack. If there are no remaining middleware functions, it moves to the route
handler or final error-handling middleware.

4. **How can you secure an Express application?**

- Answer: You can secure an Express application by using middleware such as `helmet` for
setting security-related HTTP headers, `cors` for handling cross-origin requests, and
ensuring proper validation and sanitization of user inputs. Additionally, using HTTPS, rate
limiting, and authentication mechanisms (e.g., JWT) are common security practices.

5. **What is the difference between `app.use()` and `app.get()` in Express.js?**

- Answer: `app.use()` is used to apply middleware to all routes or a subset of routes, while
`app.get()` is specifically used to define route handlers for GET requests.

6. **What are web sockets in Node.js, and how are they different from HTTP?**

- Answer: Web sockets provide full-duplex communication between the client and the
server over a single, long-lived connection. Unlike HTTP, which follows a request-response
pattern, web sockets allow both the client and server to send messages to each other at any
time without needing to establish a new connection.
7. **What is a RESTful API, and how do you create one using Node.js/Express?**

- Answer: A RESTful API follows the REST architecture, using HTTP methods like GET,
POST, PUT, and DELETE to manipulate resources. In Express, you can create a RESTful API
by defining routes corresponding to these HTTP methods and handling data in JSON format.

8. **What is the difference between synchronous and asynchronous programming in


Node.js?**

- Answer: In synchronous programming, tasks are executed sequentially, one after the
other. In asynchronous programming, tasks are executed without waiting for the previous
task to complete, allowing other tasks to run in the meantime, which improves performance
in I/O-heavy applications.

9. **How do you manage sessions in Express.js?**

- Answer: You can manage sessions in Express using the `express-session` middleware. It
allows you to store session data on the server and create unique session IDs for each client,
which can be stored in cookies.

10. **What is error handling in Express, and how do you implement it?**

- Answer: Error handling in Express can be implemented by defining error-handling


middleware. These middleware functions have four arguments (`err`, `req`, `res`, and `next`)
and are used to catch and handle errors at various stages of request processing.

Mongodb Interview Questions and


Answers
### **Beginner Level:**

1. **What is MongoDB?**
- Answer: MongoDB is a NoSQL, document-oriented database that stores data in flexible,
JSON-like documents. It is designed for high performance, high availability, and easy
scalability.

2. **What is the difference between SQL and NoSQL databases?**

- Answer: SQL databases are relational, structured, and use tables to store data with fixed
schemas. NoSQL databases like MongoDB are non-relational, flexible, and store data in
formats such as documents, key-value pairs, or graphs, allowing for dynamic schemas.

3. **What is a document in MongoDB?**

- Answer: A document in MongoDB is a set of key-value pairs (similar to JSON objects).


Documents are the basic unit of data in MongoDB and are stored in collections.

4. **What is a collection in MongoDB?**

- Answer: A collection in MongoDB is a group of documents, similar to a table in an SQL


database. Collections do not enforce a schema, so documents within the same collection can
have different structures.

5. **What is BSON in MongoDB?**

- Answer: BSON (Binary JSON) is a binary representation of JSON-like documents.


MongoDB uses BSON to encode documents and store them in the database, supporting
more data types than JSON.

### **Intermediate Level:**

1. **What are indexes in MongoDB, and why are they used?**

- Answer: Indexes in MongoDB are used to improve the performance of search queries.
They help MongoDB locate the required documents quickly, avoiding a full collection scan.
However, too many indexes can impact write performance.

2. **What is replication in MongoDB, and how does it work?**


- Answer: Replication in MongoDB is the process of synchronizing data across multiple
servers for high availability. MongoDB achieves replication using replica sets, which consist
of a primary node (handling reads and writes) and secondary nodes (maintaining copies of
the data). If the primary fails, a secondary can be promoted to primary.

3. **What is sharding in MongoDB?**

- Answer: Sharding is a method for distributing data across multiple servers or clusters in
MongoDB to ensure horizontal scalability. It is used when the size of a dataset exceeds the
capacity of a single server. Each shard contains a subset of the data.

4. **How does MongoDB handle transactions?**

- Answer: Starting with MongoDB 4.0, multi-document ACID transactions are supported.
Transactions allow multiple operations to be executed as a single unit, ensuring atomicity,
consistency, isolation, and durability.

5. **How do you perform aggregation in MongoDB?**

- Answer: MongoDB uses the aggregation framework to process and transform data in
collections. The `aggregate()` method allows you to apply a series of transformations, such
as filtering, grouping, and sorting, to your data. Common stages in an aggregation pipeline
include `$match`, `$group`, `$sort`, and `$project`.

### **Advanced Level:**

1. **What is the role of the `ObjectId` in MongoDB?**

- Answer: `ObjectId` is the default type used for the `_id` field in MongoDB. It is a 12-byte
identifier that is unique across the cluster. `ObjectId` contains information like a timestamp,
machine identifier, process ID, and a counter, ensuring uniqueness.

2. **What are the differences between embedding documents and referencing documents in
MongoDB?**

- Answer: Embedding documents means storing related data within a single document,
which is useful when the related data is accessed together. Referencing documents involves
storing related data in different collections and linking them using a reference (similar to
foreign keys). Embedding is faster for reads, while referencing helps reduce data
duplication.

3. **What is a capped collection in MongoDB?**

- Answer: A capped collection is a fixed-size collection that automatically overwrites the


oldest documents when the collection reaches its maximum size. Capped collections are
useful for use cases like logging or caching where only recent data is needed.

4. **How does MongoDB achieve horizontal scaling?**

- Answer: MongoDB achieves horizontal scaling through sharding, which distributes data
across multiple servers. Each server (or shard) holds a portion of the data, and MongoDB
automatically routes queries to the appropriate shard based on the shard key.

5. **What is the difference between the `$lookup` and `$graphLookup` operators in


MongoDB?**

- Answer: The `$lookup` operator is used to perform a left outer join between two
collections, allowing you to combine data from related collections. The `$graphLookup`
operator is used to perform recursive searches in a collection, which is useful for
hierarchical or graph data structures.

6. **Explain how MongoDB handles concurrency.**

- Answer: MongoDB uses a locking mechanism to handle concurrency. Starting from


MongoDB 3.0, it has a per-database and per-collection locking system, allowing for more
concurrency and better performance compared to older versions that used global locking.
MongoDB also supports optimistic concurrency control via the `$inc` operator and
transactions for multi-document atomic operations.

7. **What is the Aggregation Pipeline in MongoDB, and how is it different from


MapReduce?**

- Answer: The Aggregation Pipeline is a framework for processing and transforming data
in MongoDB collections using a series of stages. It is more efficient and easier to use than
MapReduce, which was an older method for data aggregation that required writing custom
JavaScript functions. The Aggregation Pipeline supports operations like filtering, grouping,
and joining, while MapReduce is more flexible but slower.

8. **What is GridFS in MongoDB?**

- Answer: GridFS is a specification for storing and retrieving large files (over 16 MB) in
MongoDB. It splits the file into smaller chunks and stores each chunk as a separate
document. GridFS is commonly used for storing large binary files like images, videos, and
audio.

9. **How do you optimize performance in MongoDB?**

- Answer: MongoDB performance can be optimized by creating proper indexes, using the
aggregation pipeline instead of MapReduce, utilizing sharding for large datasets, and
avoiding excessive use of deep document nesting. Profiling and monitoring tools like the
MongoDB Profiler can also help identify performance bottlenecks.

10. **What are MongoDB Change Streams?**

- Answer: Change Streams in MongoDB allow applications to listen for real-time changes
to data in a collection, database, or deployment. It enables features like real-time
notifications and syncing data between databases. Change streams are based on the
MongoDB replication mechanism.

SQL Interview Questions and Answers


### **Beginner Level:**

1. **What is MySQL?**

- Answer: MySQL is an open-source relational database management system (RDBMS) that


uses Structured Query Language (SQL) to manage and manipulate databases.

2. **What are the differences between SQL and MySQL?**


- Answer: SQL is a language used to query and manipulate databases, whereas MySQL is an
RDBMS that uses SQL to manage databases. MySQL is a software system, and SQL is the
language used to interact with it.

3. **What is a primary key in MySQL?**

- Answer: A primary key is a column (or a combination of columns) that uniquely


identifies each record in a table. It ensures that the value in this field is unique and not null.

4. **What is a foreign key in MySQL?**

- Answer: A foreign key is a field in a table that links to the primary key of another table. It
is used to establish relationships between tables and ensure referential integrity.

5. **What are the different types of joins in MySQL?**

- Answer: The types of joins in MySQL are:

- **INNER JOIN**: Returns records that have matching values in both tables.

- **LEFT JOIN**: Returns all records from the left table and the matched records from the
right table. Returns `NULL` for unmatched records.

- **RIGHT JOIN**: Returns all records from the right table and the matched records from
the left table.

- **FULL JOIN**: Returns records when there is a match in either table (MySQL does not
support FULL JOIN, but it can be simulated using UNION).

### **Intermediate Level:**

1. **What is normalization in MySQL?**

- Answer: Normalization is the process of organizing the columns (attributes) and tables
(relations) of a database to minimize redundancy and dependency. The main goals are to
eliminate redundant data and ensure data integrity.

2. **What are the different normal forms in database normalization?**


- Answer: The commonly used normal forms are:

- **1NF (First Normal Form)**: Ensures each column contains atomic values, and there
are no repeating groups.

- **2NF (Second Normal Form)**: Ensures that the table is in 1NF and all non-key
columns are fully dependent on the primary key.

- **3NF (Third Normal Form)**: Ensures that the table is in 2NF and all non-key columns
are not dependent on any other non-key column (i.e., no transitive dependencies).

3. **What is a transaction in MySQL?**

- Answer: A transaction is a set of SQL statements that are executed as a single unit of
work. A transaction ensures the ACID (Atomicity, Consistency, Isolation, Durability)
properties, meaning that the transaction either completes fully or does not affect the
database at all.

4. **What is the `GROUP BY` clause used for in MySQL?**

- Answer: The `GROUP BY` clause is used to group rows that have the same values in
specified columns. It is often used with aggregate functions (e.g., COUNT, SUM, AVG) to
perform calculations on each group of data.

5. **What are indexes in MySQL, and why are they used?**

- Answer: Indexes are special data structures that improve the speed of data retrieval
operations on a table by reducing the number of disk accesses. Indexes make queries faster,
but they also require additional space and maintenance overhead during write operations.

### **Advanced Level:**

1. **What are stored procedures in MySQL?**

- Answer: A stored procedure is a set of SQL statements that can be stored in the database
and executed repeatedly. It allows you to encapsulate logic and reuse code, improving
performance and maintainability.
2. **What is the difference between `CHAR` and `VARCHAR` in MySQL?**

- Answer: `CHAR` is a fixed-length data type, meaning that it always reserves the defined
space (e.g., `CHAR(10)` always stores 10 characters). `VARCHAR` is a variable-length data
type that only uses as much space as needed to store the data, with a maximum length limit.

3. **What are triggers in MySQL?**

- Answer: Triggers are SQL statements that are automatically executed or fired when
specific events occur in a table, such as `INSERT`, `UPDATE`, or `DELETE`. They can be used
to enforce business rules or automatically modify data.

4. **What are the different storage engines in MySQL?**

- Answer: The two most common storage engines in MySQL are:

- **InnoDB**: Supports transactions, foreign keys, and row-level locking. It is the default
storage engine.

- **MyISAM**: Does not support transactions or foreign keys but provides faster read
performance for some types of queries.

5. **What is database partitioning in MySQL?**

- Answer: Database partitioning is the process of dividing a large table into smaller, more
manageable pieces called partitions. Each partition is stored separately, and queries can be
optimized to work on specific partitions, improving performance for large datasets.

6. **What is MySQL replication, and how does it work?**

- Answer: MySQL replication allows data from one database server (master) to be
replicated to one or more database servers (slaves). It helps with scaling read operations,
ensuring high availability, and creating backups. Replication can be asynchronous or semi-
synchronous.

7. **What are views in MySQL, and why are they used?**


- Answer: Views are virtual tables in MySQL that are defined by a `SELECT` query. They
allow you to simplify complex queries, abstract data for security purposes, and provide
different views of the same data to different users.

8. **What is a composite primary key in MySQL?**

- Answer: A composite primary key is a primary key that consists of more than one
column. It is used when a single column is not sufficient to uniquely identify records in a
table.

9. **How do you optimize queries in MySQL?**

- Answer: Query optimization in MySQL can be done by:

- Creating and using indexes appropriately.

- Avoiding SELECT * and specifying only required columns.

- Using `EXPLAIN` to analyze the query execution plan.

- Normalizing the database schema to reduce redundancy.

- Using appropriate data types and reducing the size of data where possible.

10. **What are MySQL isolation levels, and why are they important?**

- Answer: Isolation levels in MySQL define how transaction integrity is maintained. The
four isolation levels are:

- **Read Uncommitted**: Transactions can see uncommitted changes made by other


transactions.

- **Read Committed**: A transaction only sees changes committed before it started.

- **Repeatable Read**: Ensures that if a transaction reads the same row twice, it will see
the same data both times, even if another transaction modifies the data.

- **Serializable**: The strictest isolation level, transactions are executed in a way that
ensures no two transactions can interfere with each other (as if they were serialized).
Java Interview Questions and
Answers
### **Beginner Level:**

1. **What is Java?**

- Answer: Java is a high-level, object-oriented programming language designed to have as


few implementation dependencies as possible. It is platform-independent and widely used
for building web, desktop, and mobile applications.

2. **What is the difference between JDK, JRE, and JVM?**

- Answer:

- **JDK (Java Development Kit)**: It is a software development kit used to develop Java
applications. It includes JRE and development tools.

- **JRE (Java Runtime Environment)**: It provides the runtime environment required to


execute Java applications. It includes JVM.

- **JVM (Java Virtual Machine)**: It is an abstract machine that provides the runtime
environment in which Java bytecode can be executed.

3. **What is OOP?**

- Answer: Object-Oriented Programming (OOP) is a programming paradigm based on the


concept of objects, which contain data (attributes) and methods (functions). The four main
principles of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.

4. **What are the access modifiers in Java?**

- Answer: The access modifiers in Java are:

- **private**: Accessible only within the same class.


- **default** (no modifier): Accessible within the same package.

- **protected**: Accessible within the same package and subclasses.

- **public**: Accessible from anywhere.

5. **What is the difference between `==` and `equals()` in Java?**

- Answer:

- `==` compares the references (memory addresses) of two objects to check if they point
to the same location.

- `equals()` is a method that compares the actual content (value) of two objects.

### **Intermediate Level:**

1. **What is a constructor in Java?**

- Answer: A constructor is a special method that is called when an object is instantiated. It


is used to initialize the object’s properties. Constructors have the same name as the class
and do not have a return type.

2. **What is the difference between an abstract class and an interface in Java?**

- Answer:

- **Abstract class**: Can have both abstract and concrete methods. It can contain instance
variables, and its methods can have implementations.

- **Interface**: Can only have abstract methods (before Java 8), but from Java 8 onwards,
it can have default methods. It cannot contain instance variables.

3. **What is method overloading in Java?**

- Answer: Method overloading is a feature in Java that allows a class to have more than
one method with the same name, provided their parameter lists are different (different
number or types of parameters).
4. **What is method overriding in Java?**

- Answer: Method overriding is when a subclass provides a specific implementation for a


method that is already defined in its superclass. The method in the subclass must have the
same name, return type, and parameter list as the one in the superclass.

5. **What is the difference between `ArrayList` and `LinkedList` in Java?**

- Answer:

- **ArrayList**: Uses a dynamic array to store elements. It provides fast random access to
elements but slow insertion and deletion operations.

- **LinkedList**: Uses a doubly linked list to store elements. It provides faster insertion
and deletion but slower access to elements compared to `ArrayList`.

### **Advanced Level:**

1. **What are the key principles of the SOLID design principles in Java?**

- Answer:

- **S**: Single Responsibility Principle (SRP) – A class should have one, and only one,
reason to change.

- **O**: Open/Closed Principle (OCP) – Software entities should be open for extension
but closed for modification.

- **L**: Liskov Substitution Principle (LSP) – Objects of a superclass should be


replaceable with objects of a subclass without affecting the correctness of the program.

- **I**: Interface Segregation Principle (ISP) – Clients should not be forced to implement
interfaces they don't use.

- **D**: Dependency Inversion Principle (DIP) – High-level modules should not depend
on low-level modules; both should depend on abstractions.

2. **What are Java annotations?**

- Answer: Java annotations are metadata that provide data about the program but do not
affect the program logic. They can be used to give instructions to the compiler or runtime
environments, for example, `@Override`, `@Deprecated`, and `@FunctionalInterface`.
3. **What is the Java Memory Model (JMM)?**

- Answer: The Java Memory Model defines how threads interact through memory and how
changes made by one thread to variables are made visible to other threads. It is responsible
for defining the rules for read and write operations in a multi-threaded environment.

4. **What is the difference between `HashMap` and `Hashtable` in Java?**

- Answer:

- **HashMap**: Is non-synchronized and allows one `null` key and multiple `null` values.
It is faster but not thread-safe.

- **Hashtable**: Is synchronized and thread-safe but does not allow `null` keys or values.

5. **What is the difference between `final`, `finally`, and `finalize()` in Java?**

- Answer:

- `final`: A keyword used to declare constants, prevent inheritance (final class), or prevent
method overriding (final method).

- `finally`: A block used in exception handling that executes after the `try` and `catch`
blocks, regardless of whether an exception occurred.

- `finalize()`: A method called by the garbage collector on an object when the object is no
longer reachable, just before the object is destroyed.

6. **What is reflection in Java?**

- Answer: Reflection is a feature in Java that allows a program to inspect and modify the
behavior of objects at runtime. It is used for introspection, dynamically loading classes,
calling methods, or accessing fields.

7. **What are lambda expressions in Java?**

- Answer: Introduced in Java 8, lambda expressions are a concise way to represent


anonymous methods or functions. They enable you to pass a method as an argument,
simplifying the syntax for functional interfaces.
8. **What is the Stream API in Java?**

- Answer: The Stream API, introduced in Java 8, allows developers to work with sequences
of data in a functional programming style. It supports operations like filtering, mapping, and
reducing, and is useful for processing collections of data in a declarative way.

9. **What are checked and unchecked exceptions in Java?**

- Answer:

- **Checked exceptions**: Are exceptions that are checked at compile time. The code
must handle them explicitly (e.g., `IOException`).

- **Unchecked exceptions**: Are exceptions that occur at runtime and are not checked at
compile time (e.g., `NullPointerException`, `ArithmeticException`).

10. **What is garbage collection in Java, and how does it work?**

- Answer: Garbage collection is the process by which the Java runtime automatically
reclaims memory by identifying and disposing of objects that are no longer reachable from
any references. It helps in efficient memory management and prevents memory leaks.

OOPS Interview Questions and


Answers
### **Beginner Level:**

1. **What is Object-Oriented Programming (OOP)?**

- Answer: OOP is a programming paradigm based on the concept of "objects," which can
contain data and code that manipulates that data. OOP aims to implement real-world
entities in programming.

2. **What are the four main principles of OOP?**


- Answer:

- **Encapsulation**

- **Inheritance**

- **Polymorphism**

- **Abstraction**

3. **What is a class in OOP?**

- Answer: A class is a blueprint for creating objects that defines properties and behaviors.

4. **What is an object in OOP?**

- Answer: An object is an instance of a class, containing data and methods.

5. **What is encapsulation?**

- Answer: Encapsulation is restricting access to an object's internal state and only allowing
interaction through defined methods.

6. **What is inheritance?**

- Answer: Inheritance allows one class to inherit the properties and methods of another
class.

7. **What is polymorphism?**

- Answer: Polymorphism allows methods to perform different tasks based on the object
that invokes them.

8. **What is abstraction?**

- Answer: Abstraction hides complex implementation details and exposes only the
essential features.
9. **What is the difference between a class and an object?**

- Answer: A class is a blueprint, while an object is an instance of that blueprint.

10. **What is method overloading?**

- Answer: Method overloading is defining multiple methods with the same name but
different parameters within the same class.

### **Intermediate Level:**

1. **What is method overriding?**

- Answer: Method overriding allows a subclass to provide a specific implementation of a


method already defined in its superclass.

2. **What are access modifiers in OOP?**

- Answer: Access modifiers determine the visibility of classes, methods, and attributes.
Common modifiers include `public`, `private`, `protected`, and `default`.

3. **What is an interface in OOP?**

- Answer: An interface is a contract that defines a set of methods that a class must
implement, allowing for multiple inheritance in Java.

4. **What is the difference between an abstract class and an interface?**

- Answer:

- An abstract class can have both abstract methods and concrete methods, while an
interface can only have abstract methods (Java 8 and earlier) and no state.

- A class can inherit from only one abstract class but can implement multiple interfaces.

5. **What is the Singleton Design Pattern?**


- Answer: The Singleton Design Pattern ensures that a class has only one instance and
provides a global point of access to it.

6. **What is a constructor in OOP?**

- Answer: A constructor is a special method that is called when an object is instantiated. It


is used to initialize the object's properties.

7. **What is the purpose of the `super` keyword?**

- Answer: The `super` keyword refers to the superclass and is used to call the superclass's
methods or constructors.

8. **What is multiple inheritance, and how is it achieved in Java?**

- Answer: Multiple inheritance allows a class to inherit from more than one class. In Java, it
is achieved using interfaces, as a class can implement multiple interfaces.

9. **What is the difference between shallow copy and deep copy?**

- Answer:

- A shallow copy creates a new object but copies the references of the original object's
fields.

- A deep copy creates a new object and recursively copies all fields, ensuring that changes
to the copy do not affect the original.

10. **What are the advantages of using OOP?**

- Answer: OOP provides better code organization, code reuse through inheritance,
flexibility through polymorphism, and easier maintenance and debugging.

### **Advanced Level:**

1. **What is the Factory Design Pattern?**


- Answer: The Factory Design Pattern is a creational pattern that provides an interface for
creating objects in a superclass but allows subclasses to alter the type of objects that will be
created.

2. **What is the Observer Design Pattern?**

- Answer: The Observer Design Pattern defines a one-to-many dependency between


objects so that when one object changes state, all its dependents are notified and updated
automatically.

3. **What is the Decorator Design Pattern?**

- Answer: The Decorator Design Pattern allows behavior to be added to individual objects,
either statically or dynamically, without affecting the behavior of other objects from the
same class.

4. **What is the difference between composition and inheritance?**

- Answer:

- Inheritance establishes a "is-a" relationship, where a subclass inherits from a


superclass.

- Composition establishes a "has-a" relationship, where a class contains instances of other


classes as its members.

5. **What is the Liskov Substitution Principle?**

- Answer: The Liskov Substitution Principle states that objects of a superclass should be
replaceable with objects of a subclass without affecting the correctness of the program.

6. **What is the Dependency Inversion Principle?**

- Answer: The Dependency Inversion Principle states that high-level modules should not
depend on low-level modules. Both should depend on abstractions.

7. **What is the purpose of the `final` keyword in OOP?**


- Answer: The `final` keyword is used to declare constants, prevent method overriding,
and prevent inheritance of a class.

8. **What are design patterns in OOP?**

- Answer: Design patterns are reusable solutions to common problems in software design.
They provide a standard terminology and are best practices for solving recurring design
issues.

9. **What is the difference between an object and a class in terms of memory allocation?**

- Answer: A class is a blueprint and does not occupy memory until an object is created. An
object occupies memory to store its attributes and methods defined in its class.

10. **What is encapsulation and how does it relate to data hiding?**

- Answer: Encapsulation is the bundling of data and methods that operate on that data. It
is a means of restricting access to certain details and is often used to achieve data hiding.

Spring Boot Interview Questions and


Answers
### **Beginner Level:**

1. **What is Spring Boot?**

- Answer: Spring Boot is an extension of the Spring framework that simplifies the setup
and development of new Spring applications. It provides a set of conventions and defaults to
reduce boilerplate configuration, allowing developers to create stand-alone, production-
grade applications quickly.

2. **What are the main features of Spring Boot?**

- Answer: Some main features of Spring Boot include:


- Auto-configuration: Automatically configures Spring applications based on the
dependencies present in the classpath.

- Stand-alone: Applications can be run without needing a web server.

- Spring Initializr: A web-based tool for generating Spring Boot projects with required
dependencies.

- Embedded servers: Supports embedded Tomcat, Jetty, or Undertow servers for easier
deployment.

3. **What is a Spring Boot Starter?**

- Answer: Spring Boot Starters are a set of convenient dependency descriptors that help
you get started quickly with Spring projects. They group common dependencies for specific
tasks (e.g., `spring-boot-starter-web` for web applications, `spring-boot-starter-data-jpa` for
JPA).

4. **How do you create a Spring Boot application?**

- Answer: A Spring Boot application can be created by:

1. Using Spring Initializr (https://start.spring.io) to generate a project.

2. Setting up the project structure manually with the required dependencies.

3. Using an IDE like IntelliJ IDEA or Eclipse with Spring Boot support to create a new
Spring Boot project.

5. **What is the role of the `@SpringBootApplication` annotation?**

- Answer: The `@SpringBootApplication` annotation is a convenience annotation that


combines three annotations:

- `@Configuration`: Indicates that the class can be used by the Spring IoC container as a
source of bean definitions.

- `@EnableAutoConfiguration`: Enables Spring Boot’s auto-configuration mechanism.

- `@ComponentScan`: Enables component scanning, allowing Spring to find and register


components (e.g., controllers, services) in the specified package.
6. **What is the `application.properties` file used for in Spring Boot?**

- Answer: The `application.properties` file is used to configure application-specific


properties in Spring Boot. It allows developers to customize various settings, such as
database connections, server ports, logging levels, and more.

7. **How can you run a Spring Boot application?**

- Answer: A Spring Boot application can be run in several ways:

- From the command line using Maven or Gradle: `mvn spring-boot:run` or `./gradlew
bootRun`.

- Running the `main` method in the IDE.

- Packaging the application as a JAR file and executing it using `java -jar <your-
application>.jar`.

8. **What is Spring Boot Actuator?**

- Answer: Spring Boot Actuator is a set of production-ready features that help monitor and
manage Spring Boot applications. It provides endpoints to expose application health,
metrics, environment properties, and more. Common endpoints include `/actuator/health`
and `/actuator/info`.

9. **What are RESTful web services in Spring Boot?**

- Answer: RESTful web services are web services that adhere to the principles of
Representational State Transfer (REST). In Spring Boot, RESTful services can be created
using the `@RestController` annotation, which combines `@Controller` and
`@ResponseBody` to return JSON or XML responses directly.

10. **How do you handle exceptions in Spring Boot?**

- Answer: Exceptions in Spring Boot can be handled using:

- The `@ControllerAdvice` annotation to create a global exception handler.

- The `@ExceptionHandler` annotation within a controller to handle specific exceptions.

- Custom exception classes to represent different error scenarios.


Angular Interview Questions and
Answers
### **Beginner Level:**

1. **What is Angular?**

- Answer: Angular is a platform and framework for building single-page client applications
using HTML and TypeScript. It is developed by Google and provides a robust architecture
for building web applications.

2. **What are components in Angular?**

- Answer: Components are the basic building blocks of an Angular application. Each
component consists of an HTML template, a TypeScript class that defines its behavior, and
optional CSS styles. Components control a patch of the screen called a view.

3. **What is a module in Angular?**

- Answer: A module is a container for a cohesive block of code dedicated to an application


domain, a workflow, or a closely related set of capabilities. Angular applications are
modular and typically consist of multiple modules, each containing components, services,
directives, etc.

4. **What is a service in Angular?**

- Answer: Services are reusable business logic or data access code in Angular applications.
They are used to share data and functionality between components and can be injected into
components or other services using Angular's dependency injection system.

5. **What is dependency injection in Angular?**

- Answer: Dependency injection is a design pattern that allows a class to receive its
dependencies from external sources rather than creating them itself. Angular uses a
hierarchical dependency injection system to manage the creation and sharing of services
across components.

### **Intermediate Level:**

1. **What is the purpose of Angular's `ngModule`?**

- Answer: `NgModule` is a decorator that defines an Angular module. It is used to group


related components, directives, pipes, and services into cohesive blocks of functionality.
Each Angular application has at least one root module.

2. **What are directives in Angular?**

- Answer: Directives are special markers in Angular that tell the library to attach a specific
behavior to a DOM element or to transform the DOM element and its children. There are
three types of directives: components (which are directives with a template), structural
directives (like `*ngIf`, `*ngFor`), and attribute directives.

3. **What is data binding in Angular?**

- Answer: Data binding is the process of coordinating the model (data) and the view (UI).
Angular supports several types of data binding:

- **One-way data binding**: From the component to the template (e.g., interpolation).

- **Two-way data binding**: Synchronizes data between the component and the template
using `[(ngModel)]`.

4. **What is the difference between `ngIf` and `ngSwitch`?**

- Answer:

- `ngIf` conditionally includes a template based on a boolean expression. If the expression


evaluates to true, the template is rendered; otherwise, it is removed from the DOM.

- `ngSwitch` conditionally displays one of a set of templates based on a switch expression.


It is used for multiple conditions.
5. **What are pipes in Angular?**

- Answer: Pipes are a way to transform data for display in Angular templates. They can
format dates, currencies, or custom data transformations. Pipes can be built-in (e.g.,
`DatePipe`, `CurrencyPipe`) or custom pipes created by developers.

### **Advanced Level:**

1. **What is the Angular lifecycle?**

- Answer: Angular components go through a lifecycle, managed by Angular. Key lifecycle


hooks include:

- `ngOnInit()`: Called after the component is initialized.

- `ngOnChanges()`: Called before `ngOnInit()` and whenever one or more input properties
change.

- `ngOnDestroy()`: Called just before the component is destroyed, used for cleanup.

2. **What is routing in Angular?**

- Answer: Routing is the mechanism for navigating between different views or


components in an Angular application. The Angular Router is responsible for interpreting
the URL and displaying the corresponding component based on defined routes.

3. **What are Observables in Angular?**

- Answer: Observables are a part of the RxJS library and are used for asynchronous
programming in Angular. They represent a stream of data that can be observed over time.
Observables can emit multiple values and are used in services to handle HTTP requests,
events, etc.

4. **What is the difference between `Promise` and `Observable`?**

- Answer:

- **Promise**: Represents a single value that may be available now, or in the future, or
never. It is eager and can only be used for one value.
- **Observable**: Can represent multiple values over time and is lazy, meaning it doesn’t
start emitting values until it is subscribed to.

5. **What is a guard in Angular routing?**

- Answer: Guards are services that can control whether a route can be activated,
deactivated, or can load. They are used for authentication, authorization, and other routing
conditions. Common types of guards include `CanActivate`, `CanDeactivate`, and `Resolve`.

6. **What is lazy loading in Angular?**

- Answer: Lazy loading is a design pattern that loads modules only when they are needed,
rather than loading all modules at startup. It helps to improve application performance by
reducing the initial load time.

7. **What is the difference between `@Input()` and `@Output()` in Angular?**

- Answer:

- `@Input()`: A decorator used to define input properties in a component, allowing data to


be passed from a parent component to a child component.

- `@Output()`: A decorator used to define output properties in a component, allowing the


child component to emit events to the parent component.

8. **What is a singleton service in Angular?**

- Answer: A singleton service is a service that is created only once per application,
ensuring that the same instance is shared across components. It can be created by providing
it in the root injector or using the `providedIn` property in the `@Injectable()` decorator.

9. **What is change detection in Angular?**

- Answer: Change detection is the mechanism that Angular uses to detect changes in the
model and update the view accordingly. Angular uses a zone-based change detection
strategy to determine when changes occur and update the view.

10. **What is the purpose of `ng-content` in Angular?**


- Answer: `ng-content` is a directive used for content projection in Angular components. It
allows you to insert external content into a component's template, enabling greater
flexibility in how components are composed.

You might also like