HTML_Interview_Questions - Copy (2)
HTML_Interview_Questions - Copy (2)
HTML_Interview_Questions - Copy (2)
What is HTML?
HTML stands for HyperText Markup Language. It is the standard language used to create
web pages and web applications.
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.
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.
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 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.
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 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 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 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.
Intermediate Level:
Advanced Level:
- 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.
- 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.
- Answer: Higher-order functions are functions that can take other functions as arguments
or return them as results. Examples include `map()`, `filter()`, and `reduce()`.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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:**
- 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.
- 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.
```jsx
```
- 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.
- 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:**
- 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.
- 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.
- 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.
- 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.
- 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.
- 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 `<>`.
10. **What is lazy loading in React, and how do you implement it?**
1. **What is Node.js?**
- 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.
- 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.
- 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:**
- 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).
- 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.
- 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.
- 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).
- 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.
- 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.
- 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.
- 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.
- 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?**
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.
- 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.
- 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.
- 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.
- 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.
- 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`.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
1. **What is 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.
- **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).
- 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.
- **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).
- 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.
- 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.
- 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.
- 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.
- 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.
- **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.
- 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.
- 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.
- 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.
- 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:
- **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:
- **JDK (Java Development Kit)**: It is a software development kit used to develop Java
applications. It includes JRE and development tools.
- **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:
- `==` 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.
- 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.
- 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:
- **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`.
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.
- **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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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`).
- 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.
- 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.
- **Encapsulation**
- **Inheritance**
- **Polymorphism**
- **Abstraction**
- Answer: A class is a blueprint for creating objects that defines properties and behaviors.
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: Method overloading is defining multiple methods with the same name but
different parameters within the same class.
- Answer: Access modifiers determine the visibility of classes, methods, and attributes.
Common modifiers include `public`, `private`, `protected`, and `default`.
- Answer: An interface is a contract that defines a set of methods that a class must
implement, allowing for multiple inheritance in Java.
- 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.
- Answer: The `super` keyword refers to the superclass and is used to call the superclass's
methods or constructors.
- 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.
- 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.
- Answer: OOP provides better code organization, code reuse through inheritance,
flexibility through polymorphism, and easier maintenance and debugging.
- 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.
- Answer:
- 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.
- Answer: The Dependency Inversion Principle states that high-level modules should not
depend on low-level modules. Both should depend on abstractions.
- 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.
- 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.
- 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.
- 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.
- 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).
3. Using an IDE like IntelliJ IDEA or Eclipse with Spring Boot support to create a new
Spring Boot project.
- `@Configuration`: Indicates that the class can be used by the Spring IoC container as a
source of bean definitions.
- From the command line using Maven or Gradle: `mvn spring-boot:run` or `./gradlew
bootRun`.
- Packaging the application as a JAR file and executing it using `java -jar <your-
application>.jar`.
- 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`.
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- 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)]`.
- Answer:
- 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.
- `ngOnChanges()`: Called before `ngOnInit()` and whenever one or more input properties
change.
- `ngOnDestroy()`: Called just before the component is destroyed, used for cleanup.
- 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.
- 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.
- 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`.
- 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.
- Answer:
- 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.
- 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.