Fsd Full Notes
Fsd Full Notes
FULLSTACK DEVELOPMENT
(20CS52I)
Student Name:…………………………………….…………….
Prepared by:
Siddaramaiah S R, SGL/CS
1. Determining Activities
• The first step in organizing is to identify and enumerate (to specify one after another)
the activities required to achieve the objectives of the enterprise.
• The activities will depend upon the nature and size of the enterprise.
• For instance, a manufacturing concern will have production, marketing and other.
2. Grouping of Activities
• The various activities are then classified into appropriate departments and divisions on
the basis of functions, products, territories, customers etc.
• Similar and related activities may be grouped together under one department or
division.
• Grouping of activities helps to secure specialization. Each department may be further
sub divided into sections and groups.
3. Assigning Duties
• The individual groups of activities are then allotted to different individuals on the basis
of their ability and aptitude.
• The responsibility of every individual should be defined clearly to avoid duplication of
work and overlapping of effort.
• Each person is given a specific job best suited to him and he is made responsible for its
execution.
4. Delegating Authority:
• Every individual is given the authority necessary to perform the assigned task
effectively.
• An individual cannot perform his job without the necessary authority or power.
5. Coordinating Activities:
• The activities and efforts of different individuals are then synchronized. Such co-
ordination is necessary to ensure effective performance of specialized functions.
Information Technology and Operational Technology are brought together (Integrated) to help
digital transformation.
Digital transformation is the integration of digital technology into all areas of a business,
fundamentally changing how you operate and deliver value to customers.
Digital technology: Digital technologies are electronic tools, systems, devices and resources
that generate, store or process data. Well known examples include social media, online games,
multimedia and mobile phones.
Operational Technology : Hardware and software that detects or causes a change through the
direct monitoring and/or control of physical devices, processes and events in the enterprise.
1. IKEA
First, IKEA purchased the online service TaskRabbit to help customers who don’t like
assembling their own furniture — a foray into software.
Next, they dipped into the smart home sector by developing its own products, and changing
their payment processing.
By June 2021, it was reported that they had seen a 300% increase in ecommerce sales as a
direct result of their transformation efforts.
2. Budweiser
The King of Beers became the Kings of Digital Transformation when they decided to
implement AI to revolutionise their processes.
ABinBev, the owner of Budweiser, Stella Artois, and Corona, established the ‘Beer Garage’
— a Silicon Valley-based innovation centre, where it researches, develops, and tests
technology-driven solutions.
They use it to dive deep into the brewing process to predict end-product outcomes.
3. Coca-Cola
Implemented a transformation strategy that aimed to address the numerous changes in shopper
behavior as the world has gone digital.
Their goal was to update the Coke brand “for a generation that doesn’t see a line between the
online world and the offline, reality and augmented reality.”
Their roadmap covered experiential, operational, cultural, and business. As a result they have
been able to speed time to market for new products from three months to two or less. This
results in an improved customer experience and increased sales.
Value delivered
This initiative has provided greater visibility across the company’s technology
landscape and enabled IT and OT to operate under a single model, using higher-quality
operational data.
The new approach allows management to optimize operations from a holistic perspective and
use technology more efficiently and effectively. It has also allowed the company to enhance its
focus on safety, production volume and operational costs. And it has enabled leading practices
such as predictive asset management and integrated planning and scheduling.
Finally, the unified approach to IT and OT has positioned the company to continue to
better take advantage of digital technologies. Technology professionals can work as an
integrated team to identify and address IT/OT-related problems and move quickly to replicate
improvements and innovations across the company—which will be key to realizing the
company’s transformation vision in the coming years.
1. IT Department
• IT Department is a core of every software company.
• It has created by the group of software professionals who are technical part of the
project.
• Duties within this department are divided among Developers, Project Managers and
QA specialists.
2. UX/UI Department
• Here the graphic part of the project is created.
• UX design stands for user experience design, while UI design stands for user interface
design.
• Create interfaces that are both effective and easy to use.
• As a result they design the whole application and its individual components.
• While creating the product, they work closely with the IT Department.
4. Marketing Department
• Responsible for creating the company's image on the market.
• Starting from the design of the website, through advertising, presence on industry
portals and press releases
5. HR Department
• Their main objective is to create the best possible team of dedicated and reliable
employees
• They are also aimed at staff development programs, improvement of staff efficiency
and career pathing.
• They play an important role in creating and implementing health and safety
regulations within the company.
6. Accounting and finances Department
• This department takes care of every financial aspect among the company.
• Also their aim is to control document flow and all settlements with partners.
7. Board of Directors
• They are responsible for coordinating the design, development, and implementation
of an organization's applications.
• Director of software development, your responsibilities are to oversee the
organization and daily operations of a software development.
Workflow
• A Workflow is defined as a sequence of tasks that processes data through a specific path
from initiation to completion. They can be used to structure any kind of business function
regardless of industry. Essentially, anytime data is passed between humans and/or
systems, a workflow is created.
Full-Stack Development
• Full-stack development refers to building end-to-end software solutions including
front-end and back-end development.
• Front-end refers to the front part of the application or UI which is seen by the end-user
and used for end-user interaction.
• The back-end part is related to server-side development, database, and API
development.
What is a full-stack web developer?
• Full stack web developers have the ability to design complete web applications and
websites. They work on the frontend, backend, database and debugging of web
applications or websites.
• They are proficient (Skilled or expert) in both frontend and backend languages and
frameworks, as well as in server, network and hosting environments.
Front end: It is the visible part of website or web application which is responsible for user
experience. The user directly interacts with the front end portion of the web application or
website.
• PHP:
• C++
• Java:
• Python:
• JavaScript
• [Link]
Database
• Oracle: Oracle database is the collection of data which is treated as a unit. The purpose of
this database is to store and retrieve information related to the query. It is a database server
and used to manage information.
• MongoDB: MongoDB, the most popular NoSQL database, is an open source document-
oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t
based on the table-like relational database structure but provides an altogether different
mechanism for storage and retrieval of data.
• Sql: Structured Query Language is a standard Database language which is used to create,
maintain and retrieve the relational database.
4. Update regularly
As your team works through the product backlog, remember that it’s a living document. You
can continuously add items to the backlog and prioritize or refine them as you work.
FULLSTACK DEVELOPMENT
WEEK-02
Software development in agile methodology
Define goal of product
Product goals help achieve the product vision and business objectives. Goals are a key piece of your
product strategy.
Define Epic
Agile epics are large pieces of work that can be broken down into smaller and more manageable work
items, tasks, or user stories. These series of work items share the same goal described by the epic.
Road Map
Roadmaps in Jira Software are team-level roadmaps useful for planning large pieces of work several
months in advance at the Epic level within a single project
Cost estimation
Cost estimation in software engineering is the process of predicting the resources (money, time, and
people) necessary to finish a project within the defined scope.
Risk Management
There are three main classifications of risks which can affect a software project:
1. Project risks
2. Technical risks
3. Business risks
1. Project risks: Project risks concern differ forms of budgetary, schedule, personnel, resource, and
customer-related problems.
2. Technical risks: Technical risks concern potential method, implementation, interfacing, testing, and
maintenance issue. Most technical risks appear due to the development team's insufficient knowledge
about the project.
3. Business risks: This type of risks contain risks of building an excellent product that no one need,
losing budgetary or personnel commitments, etc.
Sprint Demo
It is the opportunity for the Scrum Team to showcase to Stakeholders and the Product
Owner, things that have been done in a Sprint.
Burndown chart
Burndown chart is a major parameter used in agile software development and scrum
to detect how much work remains to be completed.
Burndown Chart is a graphical representation of work done, work to be done, the time
required for pending work done.
Sprint retrospective
The sprint retrospective is a recurring meeting held at the end of a sprint used to discuss
what went well during the previous sprint cycle and what can be improved for the next sprint.
During the Sprint Retrospective, the team discusses:
• What went well in the Sprint
• What could be improved
• What will we commit to improve in the next Sprint
Design Principles
1. Availability refers to the percentage of time that the infrastructure, system, or solution
remains operational under normal circumstances in order to serve its intended purpose
2. Performance is an indicator of how well a software system or component meets its
requirements for timeliness. Timeliness is measured in terms of response time or
throughput. The response time is the time required to respond to a request
3. Consistency defined as the requirement that a series of measurements of the same
project carried out by different raters using the same method should produce similar
results, is one of the most important aspects to be taken into account in the measurement
methods of the software.
4. Scalability is the measure of a system's ability to increase or decrease in performance
and cost in response to changes in application and system processing demands.
5. Manageability How efficiently and easily a software system can be monitored and
maintained to keep the system performing, secure, and running smoothly.
6. Software cost estimation is the process of predicting the effort required to develop a
software system.
Architecture Pattern:
1. Monolithic Architecture is like a big container, wherein all the software
components of an app are assembled and tightly coupled, i.e., each component fully
depends on each other.
As you can see in the example all the services provided by the application (Customer
Services, Cost Services, Product Services) are directly connected. So if we want to
change in code or something we have to change in all the services as well.
2. Layered architecture:
• A number of different layers are defined with each layer performing a well-defined
set of operations. Each layer will do some operations that becomes closer to machine
instruction set progressively.
• At the outer layer, components will receive the user interface operations and at the
inner layers, components will perform the operating system
interfacing(communication and coordination with OS)
• Intermediate layers to utility services and application software functions.
3. The Microservices pattern combines design patterns to create multiple services that
work interdependently to create a larger application. Because each application is small,
it's easier to update them when needed.
• Data entries have the same format and a predefined length and follow the same order.
Configuration Management
Configuration management occurs when a configuration platform is used to
automate, monitor, design and manage otherwise manual configuration
processes. System-wide changes take place across servers and networks,
storage, applications, and other managed system.
Infrastructure as Code
Infrastructure as Code (IaC) is the managing and provisioning of infrastructure
through code instead of through manual processes. With IaC, configuration
files are created that contain your infrastructure specifications, which makes it
easier to edit and distribute configurations.
Continuous Delivery
Continuous delivery lets developers automate testing beyond just unit tests so
they can verify application updates across multiple dimensions before
deploying to customers. These tests may include UI testing, load testing,
integration testing, API reliability testing, etc.
DevOps practices
DevOps practices reflect the idea of continuous improvement and automation.
Many practices focus on one or more development cycle phases. These
practices include:
• Continuous development. This practice spans the planning and coding
phases of the DevOps lifecycle. Version-control mechanisms might be involved.
Benefits of DevOps
DevOps proponents describe several business and technical benefits, many of
which can result in happier customers. Some benefits of DevOps include:
• Faster, better product delivery
• Faster issue resolution and reduced complexity
• Greater scalability and availability
• More stable operating environments
• Better resource utilization
• Greater automation
• Greater visibility into system outcomes
• Greater innovation
1. Configuration Management
2. Continuous Integration
3. Automated Testing
4. Infrastructure as Code
5. Continuous Delivery
6. Continuous Deployment
7. Continuous Monitoring
DevOps tools
Followers of DevOps practices often use certain DevOps-friendly tools as part
of their DevOps “toolchain.” The goal of these tools is to further streamline,
shorten, and automate the various stages of the software delivery workflow
(or “pipeline”). Many such tools also promote core DevOps tenets of
automation, collaboration, and integration between development and
operations teams. The following shows a sample of tools used at various
DevOps lifecycle stages.
• Plan. This phase helps define business value and requirements. Sample
tools include Jira or Git to help track known issues and perform project
management.
• Code. This phase involves software design and the creation of software
code. Sample tools include GitHub, GitLab, Bitbucket, or Stash.
• Build. In this phase, you manage software builds and versions, and use
automated tools to help compile and package code for future release to
production. You use source code repositories or package repositories that also
“package” infrastructure needed for product release. Sample tools include
Docker, Ansible, Puppet, Chef, Gradle, Maven, or JFrog Artifactory.
• Deploy. This phase can include tools that help manage, coordinate,
schedule, and automate product releases into production. Sample tools
include Puppet, Chef, Ansible, Jenkins, Kubernetes, OpenShift, OpenStack,
Docker, or Jira.
What is GitHub?
• Git is not the same as GitHub.
• GitHub makes tools that use Git.
• GitHub is the largest host of source code in the world, and has been
owned by Microsoft since 2018.
.
Git Install
You can download Git for free from the following website: [Link]
[Link]/
Fundamentals of Git
Here is a basic overview of how Git works:
1. Create a “repository” (project) with a git hosting tool (like Bitbucket)
2. Copy (or clone) the repository to your local machine
3. Add a file to your local repo and “commit” (save) the changes
4. “Push” your changes to your main branch
5. Make a change to your file with a git hosting tool and commit
6. “Pull” the changes to your local machine
7. Create a “branch” (version), make a change, commit the change
8. Open a “pull request” (propose changes to the main branch)
9. “Merge” your branch to the main branch
[CentOS ~]$
Su –
Password:
Git provides the git config tool, which allows you to set configuration variables.
Git stores all global configurations in .gitconfig file, which is located in your
Home directory. To set these configuration values as global, add the –
Global option, and if you omit –global option, then your configurations are
Specific for the current Git repository.
You can also set up system wide configuration. Git stores these values in
The /etc/gitconfig file, which contains the configuration for every user and
Repository on the system. To set these values, you must have the root rights
And use the –system option.
When the above code is compiled and executed, it produces the following
result:
Setting username
This information is used by Git for each commit.
[jerry@CentOS project]$ git config –global [Link] “Jerry Mouse”
Setting email id
This information is used by Git for each commit.
[jerry@CentOS project]$ git config –global [Link]
“jerry@tutorialspoint.c
Avoid merge commits for pulling
You pull the latest changes from a remote repository, and if these changes are
Divergent, then by default Git creates merge commits. We can avoid this via
Following settings.
jerry@CentOS project]$ git config –global [Link] always
Color highlighting
The following commands enable color highlighting for Git in the console.
[jerry@CentOS project]$ git config –global [Link] true
• Cloning a repository
As you edit files, Git sees them as modified, because you’ve changed them since
your last commit. You stage these modified files and then commit all your staged
changes, and the cycle repeats. This lifecycle is illustrated in Figure 2-1.
Basic
▪ Creating and switching to new branches
New Branches
The git branch command can be used to create a new branch. When you want to
start a new feature, you create a new branch off main using git branch new_branch
. Once created you can then use git checkout new_branch to switch to that branch.
GitHub
- Basics of distributed git
Git is distributed version control software. Version control is a way to save
changes over time without overwriting previous versions. Being distributed
means that every developer working with a Git repository has a copy of that entire
repository – every commit, every branch, every file.
Account creation and configuration
You typically configure your global username and email address after installing
Git.
…
[Link] your global username/email configuration:
[Link] the command line.
[Link] your username: git config –global [Link] “FIRST_NAME
LAST_NAME”
[Link] your email address: git config –global [Link]
“MY_NAME@[Link]”
- Create and push to repositories
➢ Create a new repository on [Link]. …
➢ Open TerminalTerminalGit Bash.
➢ Change the current working directory to your local
project.
➢ Use the init command to initialize the local directory as a
Git repository. …
➢ Add the files in your new local repository. …
➢ Commit the files that you’ve staged in your local
repository.
- Versioning
➢ Version control is a system that records changes to a file
or set of files over time so that you can recall specific
versions later. For the examples in this book, you will use
software source code as the files being version controlled,
though in reality you can do this with nearly any type of
file on a computer.
- Collaboration
➢ Collaboration is the way different people can work on the
same project together. It is like creating a group in GitHub
just like Groups in other social media. The people added
to the collaborator’s list can be able to push, merge, and
do other kinds of similar things on the project.
- Migration
➢ We’ve broken down the SVN-to-Git migration process
into 5 simple steps: Prepare your environment for the
migration. Convert the SVN repository to a local Git
repository. Synchronize the local Git repository when the
SVN repository changes. Share the Git repository with
your developers via Bitbucket.
CLOUD BASICS
Cloud infrastructure overview
Back End:
The backend part helps you manage all the resources needed to provide Cloud
computing services. This Cloud architecture part includes a security mechanism, a
large amount of data storage, servers, virtual machines, traffic control mechanisms,
etc.
Basic Concepts
There are certain services and models working behind the scene making the cloud computing
feasible and accessible to end users. Following are the working models for cloud computing:
• Deployment Models
Service Models
Services models
The three major Cloud Computing Offerings are
Many important tasks like accounting, sales, invoicing and planning all can be
performed using SaaS.
To understand in a simple terms, let compare this with painting a picture, where
you are provided with paint colors, different paint brushes and paper by your
school teacher and you just have to draw a beautiful picture using those tools.
PaaS services are constantly updated & new features added. Software developers,
web developers and business can benefit from PaaS. It provides platform to
support application development. It includes software support and management
services, storage, networking, deploying, testing, collaborating, hosting and
maintaining applications.
Deployment Models
Deployment models define the type of access to the cloud, i.e., how the cloud is located? Cloud
can have any of the four types of access: Public, Private, Hybrid, and Community.
Public Cloud
The public cloud allows systems and services to be easily accessible to the general public.
Public cloud may be less secure because of its openness.
Private Cloud
The private cloud allows systems and services to be accessible within an organization. It is
more secured because of its private nature.
Community Cloud
The community cloud allows systems and services to be accessible by a group of
organizations.
Hybrid Cloud
The hybrid cloud is a mixture of public and private cloud, in which the critical activities are
performed using private cloud while the non-critical activities are performed using public
cloud.
1. Client Infrastructure:
Client Infrastructure is a front-end component that provides a GUI. It helps users to
interact with the Cloud.
2. Application:
The application can be any software or platform which a client wants to access.
3. Service:
The service component manages which type of service you can access according to
the client’s requirements.
4. Runtime Cloud:
Runtime cloud offers the execution and runtime environment to the virtual
machines.
5. Storage:
Storage is another important Cloud computing architecture component. It provides
a large amount of storage capacity in the Cloud to store and manage data.
6. Infrastructure:
It offers services on the host level, network level, and application level. Cloud
infrastructure includes hardware and software components like servers, storage,
network devices, virtualization software, and various other storage resources that
are needed to support the cloud computing model.
7. Management:
This component manages components like application, service, runtime cloud,
storage, infrastructure, and other security matters in the backend. It also establishes
coordination between them.
8. Security:
Security in the backend refers to implementing different security mechanisms for
secure Cloud systems, resources, files, and infrastructure to the end-user.
9. Internet:
Internet connection acts as the bridge or medium between frontend and backend. It
allows you to establish the interaction and communication between the frontend
and backend.
The term cloud native refers to the concept of building and running
applications to take advantage of the distributed computing offered by
the cloud delivery model. Cloud native apps are designed and built to
exploit the scale, elasticity, resiliency, and flexibility the cloud
provides.
As defined by the Cloud Native Computing Foundation (CNCF), Cloud
native technologies empower organizations to build and run scalable
applications in public, private, and hybrid clouds. Features such as
containers, service meshes, microservices, immutable infrastructure,
and declarative application programming interfaces (APIs) best
illustrate this approach.
These features enable loosely coupled systems that are resilient,
manageable, and observable. They allow engineers to make high-
impact changes frequently and with minimal effort.
Continuous integration
CI/CD tool
CI/CD tools can help a team automate their development, deployment, and testing. Some tools
specifically handle the integration (CI) side, some manage development and deployment (CD),
while others specialize in continuous testing or related functions.
One of the best known open source tools for CI/CD is the automation server Jenkins. Jenkins
is designed to handle anything from a simple CI server to a complete CD hub.
Continuous integration refers to the build and unit testing stages of the software
release process. Every revision that is committed triggers an automated build and
test.
With continuous delivery, code changes are automatically built, tested, and prepared
for a release to production. Continuous delivery expands upon continuous
integration by deploying all code changes to a testing environment and/or a
production environment after the build stage.
[Link]
What is Jenkins?
Jenkins is an open-source Continuous Integration server written in Java for
orchestrating a chain of actions to achieve the Continuous Integration process in an
automated fashion. Jenkins supports the complete development life cycle of
software from building, testing, documenting the software, deploying, and other
stages of the software development life cycle.
Let us imagine, that there are around 10 developers who are working on a shared
repository. Some developer completes their task in 25 days while others take 30
days to complete.
Both are, in a sense, two sides of the same coin. It's difficult to decide which side to play on. Both are
highly able experts. So, they strive to deliver software on time and with zero errors. What separates
them from one another are the ideas and tactics them to meet their aims.
They are both giving contributors to the growing firm. So, they desire more flexibility and agility. Let's
look at the following points to better grasp the parallels between both Coders.
Before fixing which one to hire. So, it's a good idea to figure out what your firm's current needs are.
The following are the critical factors that must conclude.
FSD
Week 4
HTML
• HTML stands for Hyper Text Markup Language
• HTML is the standard markup language for Web pages
• HTML elements are the building blocks of HTML pages
• HTML elements are represented by <> tags
CSS
• CSS stands for Cascading Style Sheets
• CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
• CSS saves a lot of work. It can control the layout of multiple web pages all at once
• External style sheets are stored in CSS files
CSS Syntax
A CSS rule consists of a selector and a declaration block.
<html><head>
<style>
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
</style>
</head>
<body>
<h1>My First CSS Example</h1>
<p>This is a paragraph.</p>
</body>
</html>
CSS Selectors
A CSS selector selects the HTML element(s) you want to style.
We can divide CSS selectors into five categories:
• Simple selectors (select elements based on name, id, class)
• Combinator selectors (select elements based on a specific relationship between them)
• Pseudo-class selectors (select elements based on a certain state)
• Pseudo-elements selectors (select and style a part of an element)
• Attribute selectors (select elements based on an attribute or attribute value)
External CSS
With an external style sheet, you can change the look of an entire website by changing just one
file
Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.
<html>
<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
[Link]
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain
any CSS property.
<html><body>
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
</body>
</html>
What is JavaScript?
• An object-oriented computer programming language commonly used to create interactive
effects within web browsers.
• JavaScript is a text-based programming language used both on the client-side and
server-side.
• Where HTML and CSS are languages that give structure and style to web pages,
JavaScript gives web pages interactive elements that engage a user
• JavaScript programs can be inserted almost anywhere into an HTML document using
the <script> tag.
<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
JavaScript Statements
• In a programming language, the list of programming instructions are called statements.
• A JavaScript program is a list of programming statements.
• JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and
Comments.
Comments
Single line comments start with //
Multi-line comments start with /* and end with */
Variables
Variables are containers for storing data (storing data values).
In this example, x, y, and z, are variables, declared with the var keyword:
var x = 5;
var y = 6;
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x=5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML ="The value of z is: " + z;
</script>
</body>
</html>
Practice: <script>
var x = 5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML ="The value of z is: " + z;
</script>
Practice: <script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
[Link]("demo").innerHTML ="The total is: " + total;
</script>
Constants: Variables defined with const cannot be Redeclared and cannot be Reassigned.
const PI = 3.14;
Data types
Interaction
alert
This one we’ve seen already. It shows a message and waits for the user to press “OK”
<script>
alert('HI there'); // with specified content
alert(); // without any specified content
</script>
prompt
The function prompt accepts two arguments:
<script>
// prompt example
let age = prompt('How old are you?');
confirm
The syntax:
result = confirm(question);
The function confirm shows a modal window with a question and two buttons: OK and Cancel.
<script>
// confirm example
let isHappy = confirm('Are you Happy?');
alert(`You are ${isHappy}`);
</script>
Comparisons
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
Control flow
Control flow in JavaScript is how your computer runs code from top to bottom. It starts from the
first line and ends at the last line, unless it hits any statement that changes the control flow of the
program such as loops, conditionals, or functions.
Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
Install Visual Studio Code by opening the downloaded setup file and following the prompts.
VS Code extensions
VS Code extensions let you add languages, debuggers, and tools to your installation to support
your development workflow. VS Code's rich extensibility model lets extension authors plug
directly into the VS Code UI and contribute functionality through the same APIs used by VS
Code.
Bring up the Extensions view by clicking on the Extensions icon in the Activity Bar on the side
of VS Code or the View: Extensions command (Ctrl+Shift+X)
JSON
• JSON stands for JavaScript Object Notation
• JSON is a text format for storing and transporting data
• JSON is "self-describing" and easy to understand
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent
JSON Values
In JSON, values must be one of the following data types:
• a string
• a number
• an object
• an array
• a boolean
• null
Practice: <html>
<body>
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York"};
[Link]("demo").innerHTML = [Link];
or
[Link]("demo").innerHTML = myObj["name"];
</script>
</body>
</html>
[Link]()
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
Parse the data with [Link](), and the data becomes a JavaScript object.
Practice: <html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = [Link](txt);
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>
</body>
</html>
Array as JSON
When using the [Link]() on a JSON derived from an array, the method will return a
JavaScript array, instead of a JavaScript object.
Practice: <html>
<body>
<h2>Parsing a JSON Array.</h2>
<p>Data written as an JSON array will be parsed into a JavaScript array.</p>
<p id="demo"></p>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = [Link](text);
[Link]("demo").innerHTML = myArr[0];
</script>
</body>
</html>
[Link]()
A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with [Link]().
Practice: <html><body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script>
</body></html>
JavaScript Objects
Objects are variables too. But objects can contain many values.
The values are written as name:value pairs (name and value separated by a colon).
Practice: <script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Display some data from the object:
[Link]("demo").innerHTML =[Link] + " is " + [Link] + "
years old.";
or
[Link]("demo").innerHTML =person["firstName"] + " " + person["age"];
</script>
Object Properties
The name:values pairs in JavaScript objects are called properties
Accessing Object Properties
[Link]
or
objectName["propertyName"]
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
firstName John
lastName Doe
age 50
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};
Note: this refers to the person object.
Prototype
All JavaScript objects inherit properties and methods from a prototype.
The prototype property allows you to add new methods to objects constructors:
Practice: <script>
function Person(first, last, age, eye) {
[Link] = first;
[Link] = last;
}
[Link] = "English";
const myFather = new Person("John", "Doe", 50, "blue");
[Link]("demo").innerHTML =
"The nationality of my father is " + [Link];
</script>
ES6
ECMAScript (European Computer Manufacturers Association Script) is a scripting language
based on JavaScript
ECMAScript 2015 was the second major revision to JavaScript.
ECMAScript 2015 is also known as ES6 and ECMAScript 6.
Arrow functions
Arrow functions allows a short syntax for writing function expressions.
You don't need the function keyword, the return keyword, and the curly brackets.
Practice:
<script>
const x = (x, y) => x * y;
[Link]("demo").innerHTML = x(5, 5);
</script>
Template strings
Template Literals use back-ticks (``) rather than the quotes ("") to define a string:
Practice: <script>
let text = `Hello world!`;
[Link]("demo").innerHTML = text;
</script>
Interpolation
Template literals provide an easy way to interpolate variables and expressions into strings.
The method is called string interpolation.
The syntax is:
${...}
Variable Substitutions
Template literals allow variables in strings:
Practice: <script>
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
[Link]("demo").innerHTML = text;
</script>
Date objects, Array objects, and Person objects inherit from [Link].
Adding Properties and Methods to Objects
Sometimes you want to add new properties (or methods) to all existing objects of a given type.
Sometimes you want to add new properties (or methods) to an object constructor.
The JavaScript prototype property also allows you to add new methods to objects constructors:
Practice: <script>
function Person(first, last, age, eye) {
[Link] = first;
[Link] = last;
[Link] = age;
[Link] = eye;
}
[Link] = function() {
return [Link] + " " + [Link]
};
const myFather = new Person("John", "Doe", 50, "blue");
[Link]("demo").innerHTML ="My father is " + [Link]();
</script>
The Spread (...) Operator
The ... operator expands an iterable (like an array) into more elements:
Practice: <script>
const cars1 = ["Saab", "Volvo", ..."BMW"];
const cars2 = ["Fiat", "Toyota"];
const combined = [cars1, ...cars2];
[Link]("demo").innerHTML = combined;
</script>
Map
Creating a Map from an Array
A Map holds key-value pairs where the keys can be any datatype.
A Map remembers the original insertion order of the keys.
A Map has a property that represents the size of the map
new Map()
You can create a Map by passing an Array to the new Map() constructor:
Practice: <script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");
</script>
[Link]()
You can add elements to a Map with the set() method:
Practice:
<script>
// Create a Map
const fruits = new Map();
// Set Map Values
[Link]("apples", 500);
[Link]("bananas", 300);
[Link]("oranges", 200);
[Link]("demo").innerHTML = [Link]("apples");
</script>
Map Methods
Method Description
entries() Returns an iterator object with the [key, value] pairs in a Map
Property Description
JavaScript Set
A JavaScript Set is a collection of unique values.
Each value can only occur once in a Set.
A Set can hold any value of any data type.
Set Methods
Method Description
Property Description
Why TypeScript?
• TypeScript uses compile time type checking. Which means it checks if the specified
types match before running the code, not while running the code
• JavaScript is better suited for small-scale applications, while TypeScript is better for
larger applications.
• TypeScript is better than JavaScript in terms of language features, reference validation,
project scalability, collaboration within and between teams, developer experience, and
code maintainability.
To verify the installation was successful, enter the following command in the Terminal Window.
node -v
npm -v
Step-2 Install TypeScript. To install TypeScript, enter the following command in the Terminal
Window.
• npm install typescript --save-dev //As dev dependency
• npm install typescript -g //Install as a global module
or
• npm install -g typescript
• npm install typescript@latest -g //Install latest if you have an older version
Step-3 To verify the installation was successful, enter the command $ tsc -v in the Terminal
Window.
Basic Types
Built-in Data
Type keyword Description
Null null It is used when an object does not have any value
Example
let a: null = null;
let b: number = 123;
let c: number = 123.456;
let d: string = ‘Geeks’;
let e: undefined = undefined;
let f: boolean = true;
[Link](a);
[Link](b);
[Link](c);
[Link](d);
[Link](e);
[Link](f);
let a: any = null;
let b: any =123;
let c: any = 123.456;
let d: any = ‘Geeks’;
let e: any = undefined;
let f: any = true;
TypeScript If Statement:
If statement is used to execute a block of statements if specified condition is true.
if(condition){
//Block of TypeScript statements.
}
Example
var num:number = 2;
if(num==1){
[Link]("TypeScript Statement 1");
}
else if(num==2){
[Link]("TypeScript Statement 2");
}
else if(num==3){
[Link]("TypeScript Statement 3");
}
else{
[Link]("TypeScript Statement n");
}
for...of Loop
TypeScript includes the for...of loop to iterate and access elements of an array, list, or tuple
collection.
let arr = [10, 20, 30, 40];
for (var val of arr) {
[Link](val); // prints values: 10, 20, 30, 40
}
for...in Loop
Another form of the for loop is for...in. This can be used with an array, list, or tuple.
let arr = [10, 20, 30, 40];
for (var index in arr) {
[Link](index); // prints indexes: 0, 1, 2, 3
[Link](arr[index]); // prints elements: 10, 20, 30, 40
}
let i: number = 2;
while (i < 4) {
[Link]( "Block statement execution no." + i )
i++;
}
do..while loop
The do..while loop is similar to the while loop, except that the condition is given at the end of
the loop. The do..while loop runs the block of code at least once before checking for the
specified condition.
do {
// code block to be executed
}
while (condition expression);
let i: number = 2;
do {
[Link]("Block statement execution no." + i )
i++;
} while ( i < 4)
Functions
In TypeScript, functions can be of two types: named and anonymous.
Named Functions
A named function is one where you declare and call a function by its given name.
function display() {
[Link]("Hello TypeScript!");
}
display(); //Output: Hello TypeScript
Anonymous Function
• An anonymous function is one which is defined as an expression.
• This expression is stored in a variable.
• So, the function itself does not have a name.
• These functions are invoked using the variable name that the function is stored in.
An anonymous function can also include parameter types and return type.
let Sum = function(x: number, y: number) : number
{
return x + y;
}
Sum(2,3); // returns 5
Function Parameters
Parameters are values or arguments passed to a function. In TypeScript, the compiler expects
a function to receive the exact number and type of arguments as defined in the function
signature.
function Greet(greeting: string, name: string ) : string {
return greeting + ' ' + name + '!';
}
Greet('Hello','Steve');
Default Parameters
TypeScript provides the option to add default values to parameters.
function Greet(name: string, greeting: string = "Hello") : string {
return greeting + ' ' + name + '!';
}
Greet('Steve');//OK, returns "Hello Steve!"
Modern UI technologies
1. React
2. Angular
3. Flutter
4. [Link]
5. JQuery
6. Emberjs
7. Semantic UI
8 Backbonejs
9. Foundation
10. Svelte
Week 5
Introduction to React
React is an open source frontend JavaScript library for building complex UIs; it allows the
programmers to create complex UIs from smaller components.
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
Test that [Link] and npm were installed successfully by running the commands
node -v
npm -v.
Step 2:
npx create-react-app myapp
cd myapp
npm start
What is [Link]?
• [Link] is an open source server environment (free)
• [Link] runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• [Link] uses JavaScript on the server
What is JSX?
• JSX stands for JavaScript XML.
• JSX allows us to write HTML in React.
• JSX makes it easier to write and add HTML in React.
• Consider this variable declaration:
• const element = <h1>Hello, world!</h1>;
• JSX is a XML syntax extension. Just like HTML, JSX tags can have a tag names,
attributes, and children. If an attribute is wrapped in curly braces, the value is a
JavaScript expression.
Expressions in JSX
With JSX you can write expressions inside curly braces { }
The expression can be a React variable, or property, or any other valid JavaScript expression.
JSX will execute the expression and return the result
Ex:
import React from 'react';
import ReactDOM from 'react-dom/client';
const name='niranjan';
const element=<h1>Hello, { name }</h1>;
const root = [Link]([Link]('root'));
[Link](element);
Ex2:
import React from 'react';
import ReactDOM from 'react-dom/client';
Ex3:
import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
const root = [Link]([Link]('root'));
[Link](myElement);
Rendering
React renders HTML to the web page by using a function called render().
The purpose of the function is to display the specified HTML code inside the specified
HTML element.
Rendering Elements
Rendering an Element in React: In order to render any element into the Browser DOM, we
need to have a container or root DOM element. It is almost a convention to have a div
element with the id=”root” or id=”app” to be used as the root DOM element. Let’s suppose
our [Link] file has the following statement inside it.
<div id="root"></div>
Filename [Link]: Now, in order to render a simple React Element to the root node, we
must write the following in the [Link] file.
import React,{ Component } from 'react';
class App extends Component {
render() {
return (
<div>
<h1>Welcome to GeeksforGeeks!</h1>
</div>
);
}
} export default App;
React-DOM
ReactDOM is a package that provides DOM specific methods that can be used at the top
level of a web app to enable an efficient way of managing DOM elements of the web page.
Pre-requisite: To use the ReactDOM in any React web app we must first import
ReactDOM from the react-dom package by using the following code snippet:
render() Function
This function is used to render a single React Component or several Components wrapped
together in a Component or a div element.
[Link](element, container, callback)
Parameters: This method can take a maximum of three parameters as described below.
• element: This parameter expects a JSX expression or a React Element to be rendered.
• container: This parameter expects the container in which the element has to be
rendered.
• callback: This is an optional parameter that expects a function that is to be executed
once the render is complete.
Functional Components
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
Class Components
A class component must include the extends [Link] statement.
The component also requires a render() method, this method returns HTML.
Rendering a Component
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
const root = [Link]([Link]('root'));
[Link](<Car />);
Composing Components
function Welcome(props) {
return <h1>Hello, {[Link]}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div> );
}
const root = [Link]([Link]('root'));
[Link](<App />);
function Name(props) {
return <h2>My name { [Link] }!</h2>;
}
function Display() {
return (
<>
<Name name="Niranjan" />
</>
);
}
What is state?
React has another special built-in object called state, which allows components to create and
manage their own data. So unlike props, components cannot pass data with state, but they can
create and manage it internally.
render() {
return (
<div>
<p>{[Link]}</p>
<p>{[Link]}</p>
</div>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Test />);
getDerivedStateFromProps
The getDerivedStateFromProps() method is called right before rendering the element(s) in
the [Link] is the natural place to set the state object based on the initial props.
It takes state as an argument, and returns an object with changes to the state.
import React from 'react';
import ReactDOM from 'react-dom/client';
render
The render() method is required, and is the method that actually outputs the HTML to the
DOM.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends [Link] {
render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Header />);
componentDidMount
The componentDidMount() method is called after the component is rendered.
This is where you run statements that requires that the component is already placed in the
DOM.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends [Link] {
constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Header />);
Updating
A component is updated whenever there is a change in the component's state or props.
React has five built-in methods that gets called, in this order, when a component is updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
Unmounting
The next phase in the lifecycle is when a component is removed from the DOM,
or unmounting as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
• componentWillUnmount()
Error Handling
Error Handling methods are called when there is an error during rendering, in a lifecycle
method, or in the constructor of any child component.
• static getDerivedStateFromError()
• componentDidCatch()
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if ([Link]) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return [Link];
}
}
Handling Events
React events are written in camelCase syntax:
onClick instead of onclick.
React event handlers are written inside curly braces:
onClick={shoot} instead of onClick="shoot()".
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
const root = [Link]([Link]('root'));
[Link](<Football />);
Passing Arguments
To pass an argument to an event handler, use an arrow function.
import React from 'react';
import ReactDOM from 'react-dom/client';
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
const root = [Link]([Link]('root'));
[Link](<Football />);
Conditional Rendering
if Statement
We can use the if JavaScript operator to decide which component to render.
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = [Link];
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
const root = [Link]([Link]('root'));
// Try changing to isLoggedIn={true}:
[Link](<Greeting isLoggedIn={false} />);
Ternary Operator
condition ? true : false
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = [Link];
return (
<>
{ isLoggedIn ? <UserGreeting/> : <GuestGreeting/> }
</>
);
}
const root = [Link]([Link]('root'));
// Try changing to isLoggedIn={true}:
[Link](<Greeting isLoggedIn={true} />);
Use of HTML tags in forms like select, input, file, textarea, etc.
<html>
<head>
<title>Form Elements</title>
</head>
<body>
<form>
<lable>Text Box</lable>
<input type="text" id="t1" name="name" value=""/><br><br>
Radio Button: <br>
<input type="radio" id="r1" name="" value=""/>Male<br> <br>
<input type="radio" id="r1" name="" value=""/>FeMale<br><br>
Check Box:<input type="checkbox" id="c1" name="" value=""/><br><br>
File:<input type="file" id="e1" name="file" value=""/><br><br>
Select:<br>
<label>Sem</label>
<select name="sem" id="sem">
<option value="1">1 Sem</option>
<option value="2">2 Sem</option>
</select><br><br>
Text Area:<br>
<textarea id="ta1" name="textarea" rows="4" cols="50">
At [Link] you will learn how to make a website.
</textarea><br><br>
<fieldset>
<legend>Personal Details:</legend>
<label>First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label>Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
</fieldset><br><br>
Controlled components
• In HTML, form elements such as <input>, <textarea>, and <select> typically
maintain their own state and update it based on user input.
• In React, mutable state is typically kept in the state property of components, and only
updated with setState().
return (
<form onSubmit={[Link]}>
<label>Pick your favorite flavor:
<select value={[Link]} onChange={[Link]}>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
The file input Tag
Uncontrolled components
• In a controlled component, form data is handled by a React component. The
alternative is uncontrolled components, where form data is handled by the DOM
itself.
• To write an uncontrolled component, instead of writing an event handler for every
state update, you can use a ref to get form values from the DOM.
handleSubmit(event) {
alert('A name was submitted: ' + [Link]);
[Link]();
}
render() {
return (
<form onSubmit={[Link]}>
<label>
Name:
<input type="text" ref={[Link]} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
const root = [Link]([Link]('root'));
[Link](<NameForm />);
}
render() {
return (
<form onSubmit={[Link]}>
<label>Upload file:
<input type="file" ref={[Link]} />
</label>
<br />
<button type="submit">Submit</button>
</form>
); }}
const root = [Link]([Link]('root'));
[Link](<FileInput />);
Lifting State Up
In React, it is recommended to make a common pattern while using the same state in multiple
components. “Lifting state up” is a common pattern used in React to share state among
multiple components to avoid complex and unnecessary patterns for state management.
}
.btn{
color: white;
display: block;
margin: 10px auto;
}
.messages{
display: flex;
justify-content: center;
}
Filename: [Link]
import './[Link]';
import Form from "./Form"
function App() {
return (
<div className="App">
<Form />
</div>
);
}
export default App;
Filename: [Link]
import { useState } from 'react';
export default function Form() {
// States for registration
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// States for checking the errors
const [submitted, setSubmitted] = useState(false);
const [error, setError] = useState(false);
}}>
<h1>User {name} successfully registered!!</h1>
</div>
);
};
<label className="label">Email</label>
<input onChange={handleEmail} className="input"
value={email} type="email" />
<label className="label">Password</label>
<input onChange={handlePassword} className="input"
value={password} type="password" />
<button onClick={handleSubmit} className="btn" type="submit">
Submit
</button>
</form>
</div>
);
}
Week 6
Context
• Context provides a way to pass data through the component tree without having to pass
props down manually at every level.
• In a typical React application, data is passed top-down (parent to child) via props.
• Context provides a way to share values between components without having to explicitly
pass a prop through every level of the tree.
return (
<[Link] value={value}>
<MyComponent />
</[Link]>
);
}
function MyComponent() {
const value = useContext(Context);
return <span>{value}</span>;
}
const root = [Link]([Link]('root'));
[Link](<MyComponent/>);
By using Props
import React from 'react';
import ReactDOM from 'react-dom/client';
function Name(props) {
return <h2>My name { [Link] }!</h2>; }
function Display() {
return (
<>
<Name name="Niranjan" />
</>
);
}
const root = [Link]([Link]('root'));
[Link](<Display />);
React Fragments
• Allow you to wrap or group multiple elements without adding an extra node to the DOM.
• This can be useful when rendering multiple child elements/components in a single parent
component.
React Router
• React Router is a standard library for routing in React.
• It enables the navigation among views of various components in a React Application,
allows changing the browser URL, and keeps the UI in sync with the URL
• Route params are parameters whose values are set dynamically in a page’s URL.
• This allows a route to render the same component while passing that component the
dynamic portion of the URL, so that it can change its data based on the parameter.
• Examples include things like IDs for products, books, movies, users etc
<Route exact path="/movie/:id" component={MovieDetailsContainer} />
function App() {
return <h1>Hello React Router</h1>;
}
[Link](
<BrowserRouter>
<App />
</BrowserRouter>,
[Link]("root")
);
<Route path="/">
<Home />
</Route>
</Switch>
</div>
ii. The <NavLink> is a special type of <Link> that can style itself as “active” when
its to prop matches the current location.
Syntax: <NavLink to="/react" activeClassName="hurray">
React
</NavLink>
iii. Any time that you want to force navigation, you can render a <Redirect>. When
a <Redirect> renders, it will navigate using its to prop.
Syntax: <Redirect to="/login" />
[Link]
const Blogs = () => {
return <h1>Blog Articles</h1>;
};
[Link]
const Contact = () => {
return <h1>Contact Me</h1>;
};
[Link]
const Home = () => {
return <h1>Home</h1>;
};
export default Home;
[Link]
import { Outlet, Link } from "react-router-dom";
<Outlet />
</>
)
};
[Link]
const NoPage = () => {
return <h1>404</h1>;
};
useState
• The React useState Hook allows us to track state in a function component.
• State generally refers to data or properties that need to be tracking in an application.
• To use the useState Hook, we first need to import it into our component.
Syntax: import { useState } from "react";
Initialization
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("");
}
useEffect:
• The useEffect Hook allows you to perform side effects in your components.
• Some examples of side effects are: fetching data, directly updating the DOM, and timers.
• useEffect accepts two arguments. The second argument is optional.
Syntax: useEffect(<function>, <dependency>)
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
useContext
• React Context is a way to manage state globally.
• It can be used together with the useState Hook to share state between deeply nested
components more easily than with useState alone.
Context Provider: Wrap child components in the Context Provider and supply the state value.
useContext: To use the Context in a child component, we need to access it using
the useContext Hook.
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";
const UserContext = createContext();
function Component1() {
const [user, setUser] = useState("Jesse Hall");
return (
<[Link] value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</[Link]>
);
}
function Component2() {
return (
<>
<h1>Component 2</h1>
<Component3 />
</>
);
}
useReducer
• The useReducer Hook is similar to the useState Hook.
• It allows for custom state logic.
• If you find yourself keeping track of multiple pieces of state.
Syntax: useReducer(<reducer>, <initialState>)
• The reducer function contains your custom state logic and the initialStatecan be a simple
value but generally will contain an object.
Example:
import React, { useReducer } from "react";
return (
<div>
<h2>{count}</h2>
<button onClick={() => dispatch("add")}>
add
</button>
<button onClick={() => dispatch("subtract")}>
subtract
</button>
<button onClick={() => dispatch("reset")}>
reset
</button>
</div>
);
};
Custom Hooks
• Hooks are reusable functions.
• When you have component logic that needs to be used by multiple components, we can
extract that logic to a custom Hook.
• Custom Hooks start with "use". Example: useFetch.
Data Structure:
A data structure is a specialized format for organizing, processing, retrieving and
storing data.
Database Concepts:
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database management
system (DBMS).
• Database Schema: It is a design of the database.
• Data Constraints: Constraints are used to put some restriction on the table.
• Data dictionary or Metadata: Metadata is known as the data about the data
• Database instance: used to define the complete database environment and its
components.
• Query: query is used to access data from the database.
• Data manipulation: manipulation can be done using three main operations that is
Insertion, Deletion, and updation.
• Data Engine: used to create and manage various database queries.
Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request, produce
the response, then send a response back to the webserver.
import [Link].*;
public class Main {
public static void main(String args[]){
List<String> mySubjects = new ArrayList<>();
[Link]("Java");
[Link]("Spring");
[Link]("My Subjects:");
for(String subject : mySubjects){
[Link](subject);
}
}
}
Set
• A set represents a group or collection of items. Set has a special property that is unique
items, it can not contain a duplicate item or element. It extends the collection interface.
import [Link].*;
public class Main {
public static void main(String args[]){
Set<String> mySubjects = new HashSet<>();
[Link]("Java");
[Link]("Spring");
[Link]("My Subjects:");
for(String subject : mySubjects){
[Link](subject);
}
}
}
Map
• It represents a group of special elements or objects. Every map element or object contains
key and value pair. A map can’t contain duplicate keys and one key can refer to at most
one value.
import [Link].*;
public class Main {
[Link](1,"Java");
[Link](2,"Spring");
for([Link] subject : [Link]())
[Link]([Link]()+" - "+[Link]());
}
}
Thread:
• Threads allows a program to operate more efficiently by doing multiple things at the
same time.
• Threads can be used to perform complicated tasks in the background without interrupting
the main program.
Install java editor (Eclipse for Enterprise Java) and configure workspace
Step 1) Installing Eclipse
Open your browser and type [Link]
Redux
Redux is used by ReactJS for building the user interface and to manage the application
state. The official React binding for Redux is React Redux which is used to read data from
a Redux Store, and dispatch Actions to the Store to update data. It also helps the apps to
scale.
State Management with Redux
State management is essentially a way to facilitate communication and sharing of data
across components. It creates a tangible data structure to represent the state of your app
that you can read from and write to.
Week 7
Basics of Apache Maven
• Apache Maven is a software project management and comprehension tool.
• Based on the concept of a project object model (POM), Maven can manage a project's
build, reporting and documentation from a central piece of information.
• Using maven we can build and manage any Java based project.
Understanding [Link]
• POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an
XML file that resides in the base directory of the project as [Link].
• The POM contains information about the project and various configuration detail used by
Maven to build the project(s).
• POM also contains the goals and plugins. While executing a task or goal, Maven looks
for the POM in the current directory. It reads the POM, gets the needed configuration
information, and then executes the goal.
• Some of the configuration that can be specified in the POM are following
• project dependencies
• plugins
• goals
• build profiles
• project version
• developers
• mailing list
Before creating a POM, we should first decide the project group (groupId), its name (artifactId)
and its version as these attributes help in uniquely identifying the project in repository.
POM Example
<project xmlns = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
</project>
It should be noted that there should be a single POM file for each project.
• All POM files require the project element and three mandatory fields: groupId, artifactId,
version.
• Projects notation in repository is groupId:artifactId:version.
• Minimal requirements for a POM −
1 Project root
This is project root tag. You need to specify the basic schema settings such as apache
schema and [Link] specification.
2 Model version
Model version should be 4.0.0.
3 groupId
This is an Id of project's group. This is generally unique amongst an organization or a
project. For example, a banking group [Link] has all bank related projects.
4 artifactId
This is an Id of the project. This is generally name of the project. For example,
consumer-banking. Along with the groupId, the artifactId defines the artifact's location
within the repository.
5 version
This is the version of the project. Along with the groupId, It is used within an artifact's
repository to separate versions from each other. For example −
[Link]:consumer-banking:1.0
[Link]:consumer-banking:1.1.
What is Spring?
• The Spring Framework (Spring) is an open-source application framework that provides
infrastructure support for developing Java applications.
• One of the most popular Java Enterprise Edition (Java EE) frameworks, Spring helps
developers create high performing applications using plain old Java objects (POJOs).
• Spring is a lightweight framework. It can be thought of as a framework of
frameworks because it provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc.
Why Spring?
1. Easy, Simple, and Lightweight
• Spring is easy to learn and implement which is composed of modules where we can
write spring applications normally with interfaces and abstract classes just like java
applications.
• Spring helps in coupling and wiring the components which make working with Spring
easier and simpler.
• It is lightweight as we can inject dependencies as per our need
3. MVC Pattern
• Model View Controller which helps in separating implementation and business logic
• The view is where requests are received first which are taken by the controller to the
corresponding model for results which are then taken to view to show at the front side
of the application.
5. Modular Design
• It is divided into components such as core container, data access / integration, web, and
test which work together but independently.
• Implementation can also be divided in Spring according to the MVC pattern
7. Dependency Injection
• Dependency Injection helps in decreasing coupling and dependency between classes
in Spring projects so that the program becomes maintainable and reusable.
• Modules of one project can be used effectively in another project like a login page, and
registration page which not only saves them time but also promotes code reusability
Important terms
Autowiring - The process by which Spring identifies dependencies and matches and populates
them.
Bean - A Spring bean is an object that is instantiated, created, and managed by the IoC container.
Beans are the backbone of an application.
Dependency injection - A programming design pattern that makes code loosely coupled,
meaning that any change in the application of one, will not affect the other.
Inversion of control (IoC) - Taking control away from the class and giving it to the Spring
Framework.
Inversion of control container - This is the core of the Spring Framework where objects are
created, wired together, configured, and managed throughout their life cycle.
Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language modules
• The Core module provides the fundamental parts of the framework, including the IoC
and Dependency Injection features.
• The Bean module provides BeanFactory, which is a sophisticated implementation of the
factory pattern.
• The Context module builds on the solid base provided by the Core and Beans modules
and it is a medium to access any objects defined and configured. The ApplicationContext
interface is the focal point of the Context module.
• The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules
• The JDBC module provides a JDBC-abstraction layer that removes the need for tedious
JDBC related coding.
• The ORM module provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• The Java Messaging Service JMS module contains features for producing and consuming
messages.
• The Transaction module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your POJOs.
Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules
• The Web module provides basic web-oriented integration features such as multipart file-
upload functionality and the initialization of the IoC container using servlet listeners and a
web-oriented application context.
• The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-way
communication between the client and the server in web applications.
• The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
Miscellaneous
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test
modules
• The AOP module provides an aspect-oriented programming implementation allowing
you to define method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated.
• The Aspects module provides integration with AspectJ, which is again a powerful and
mature AOP framework.
• The Instrumentation module provides class instrumentation support and class loader
implementations to be used in certain application servers.
• The Messaging module provides support for STOMP as the WebSocket sub-protocol to
use in applications. It also supports an annotation programming model for routing and
processing STOMP messages from WebSocket clients.
• The Test module supports the testing of Spring components with JUnit or TestNG
frameworks.
SpringBoot
• Spring Boot is an open source Java-based framework used to create a micro Service.
• Spring Boot provides a good platform for Java developers to develop a stand-alone and
production-grade spring application that you can just run. You can get started with
minimum configurations without the need for an entire Spring configuration setup
Advantages
Spring Boot offers the following advantages to its developers −
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time
Why SpringBoot?
• It provides a flexible way to configure Java Beans, XML configurations, and Database
Transactions.
It aims to simplify Java EE It aims to shorten the code length and provide the
development that makes developers easiest way to develop Web Applications.
more productive.
The primary feature of the Spring The primary feature of Spring Boot
Framework is dependency injection. is Autoconfiguration. It automatically configures the
classes based on the requirement.
It helps to make things simpler by It helps to create a stand-alone application with less
allowing us to develop loosely configuration.
coupled applications.
To test the Spring project, we need to Spring Boot offers embedded server such
set up the sever explicitly. as Jetty and Tomcat, etc.
It does not provide support for an in- It offers several plugins for working with an
memory database. embedded and in-memory database such as H2.
Developers manually define Spring Boot comes with the concept of starter in
dependencies for the Spring project [Link] file that internally takes care of downloading
in [Link]. the dependencies JARs based on Spring Boot
Requirement.
Annotations
Annotations are used to provide supplemental information about a program.
• Annotations start with ‘@’.
• Annotations help to associate metadata (information) to the program elements i.e. instance
variables, constructors, methods, classes, etc.
• Annotations basically are used to provide additional information, so could be an alternative
to XML and Java marker interfaces.
@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}
@Component
Annotate your other components (for example REST resource classes) with @Component
@Component
public class ContactResource {
...
}
@Autowired
Let Spring auto-wire other beans into your classes using @Autowired annotation.
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyDAO companyDAO;
...
}
@Transactional
Configure your transactions with @Transactional spring annotation.
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyDAO companyDAO;
@Transactional
public Company findByName(String name) {
@Scope
To change default behavior, use @Scope spring annotation.
@Component
@Scope("request")
public class ContactResource {
...
}
Practice:
Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface.
Resource resource=new ClassPathResource("[Link]");
Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext
interface.
ApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");
ComponentScanning
• we use the @ComponentScan annotation along with the @Configuration annotation to
specify the packages that we want to be scanned.
• @ComponentScan without arguments tells Spring to scan the current package and all of
its sub-packages.
@Configuration @ComponentScan
public class SpringComponentScanApp {
private static ApplicationContext applicationContext;
@Bean
public ExampleBean exampleBean() {
return new ExampleBean();
}
public static void main(String[] args) {
applicationContext = new
AnnotationConfigApplicationContext([Link]);
for (String beanName : [Link]()) {
[Link](beanName);
}
}
}
package [Link];
// ...
@Component
public class Cat {}
package [Link];
// ...
@Component
public class Dog {}
DI in spring Boot
Dependency Injection is the ability of an object to supply dependencies of another object.
It mainly has three classes involved:
• Client Class: This is the dependent class and is dependent on the Service class.
• Service Class: This class provides a service to the client class.
• Injector Class: This class is responsible for injecting the service class object into the client
class
Autowiring
Autowiring feature of spring framework enables you to inject the object dependency implicitly.
It internally uses setter or constructor injection.
Qualifier
@Qualifier is an annotation used to specify which Spring managed bean should be injected
via @Autowired.
Bean
• Any object in the Spring framework that we initialize through Spring container is called
Spring Bean.
• Any normal Java POJO class can be a Spring Bean if it's configured to be initialized via
container by providing configuration metadata information.
• In Spring, the objects that form the backbone of your application and that are managed by
the Spring IoC container are called beans.
• A bean is an object that is instantiated, assembled, and managed by a Spring IoC
container.
1 singleton
This scopes the bean definition to a single instance per Spring IoC container (default).
2 prototype
This scopes a single bean definition to have any number of object instances.
3 request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.
4 session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.
5 global-session
This scopes a bean definition to a global HTTP session. Only valid in the context of a
web-aware Spring ApplicationContext.
The first step is to split the code and convert delivery management into a separate, loosely
coupled module within the monolith.
Step 2: Split the database
The second step is split the database and define a separate database schema for the ftgo-delivery-
service module.
The third step of the refactoring process is to define a standalone Delivery Service and deploy it.
The service does not, however, handle production traffic. Instead, it can, for example, be tested
in production.
The fourth step of the refactoring process is to use the standalone Delivery Service.
Step 5: Remove the delivery management functionality from the FTGO monolith
The fifth step of the refactoring process is to remove the now obsolete delivery management
logic from the monolith.
Week 8
What is an Application Programming Interface (API)?
Application Programming Interface (API) is a software interface that allows two
applications or software’s to interact, communicate and exchange data with each other
without any user intervention.
API is a collection of software functions and procedures.
API types (Open APIs, Partner APIs, Internal APIs, Composite APIs)
There are mainly four main types of APIs:
• Open APIs: These types of APIs are publicly available to use like OAuth APIs from
Google. It has also not given any restriction to use them. So, they are also known as
Public APIs.
• Partner APIs: Specific rights or licenses to access this type of API because they are not
available to the public.
• Internal APIs: Internal or private. These APIs are developed by companies to use in
their internal systems. It helps you to enhance the productivity of your teams.
• Composite APIs: This type of API combines different data and service APIs.
HTTP working
• As a request-response protocol, HTTP gives users a way to interact with web resources such
as HTML files by transmitting hypertext messages between clients and servers. HTTP
clients generally use Transmission Control Protocol (TCP) connections to communicate
with servers.
HTTP Method (GET, POST, PUT, DELETE)
1. GET requests a specific resource in its entirety
2. POST adds content, messages, or data to a new page under an existing web resource
3. PUT directly modifies an existing web resource or creates a new URI if need be
4. DELETE gets rid of a specified resource
Features:
• Idiomatic persistence : It enables you to write the persistence classes using object
oriented classes.
• High Performance : It has many fetching techniques and hopeful locking techniques.
• Reliable : It is highly stable and eminent. Used by many industrial programmers.
Benefits:
• It speeds up development time for teams.
• Decreases the cost of development.
• Handles the logic required to interact with databases.
• Improves security. ORM tools are built to eliminate the possibility of SQL injection
attacks.
• You write less code when using ORM tools than with SQL.
Basics of REST
Evolution of API
Overview of REST
• Representational State Transfer (REST) is an architectural style that defines a set of
constraints(rules) to be used for creating web services.
• REST API is a way of accessing web services in a simple and flexible way without
having any processing.
• REST technology is generally preferred to the more robust Simple Object Access
Protocol (SOAP) technology, simple and flexible making it more suitable for internet
usage.
• It’s used to fetch or give some information from a web service. All communication
done via REST API uses only HTTP request.
Working
• A request is sent from client to server in the form of a web URL as HTTP GET or
POST or PUT or DELETE request.
• After that, a response comes back from the server in the form of a resource which can
be anything like HTML, XML, Image, or JSON.
• But now JSON is the most popular format being used in Web Services.
HTTP methods
Following four HTTP methods are commonly used in REST based architecture.
• GET − Provides a read only access to a resource.
• POST − Used to create a new resource.
• DELETE − Used to remove a resource.
• PUT − Used to update a existing resource or create a new resource.
Connector View: A connector view of architecture tells on the mechanics of the communication
between components.
Data View: A data view of architecture tells the application state as information flows through the
components.
4. Modifiability: Modifiability represents the ease at which changes can be incorporated into the
architecture.
5. Visibility: Visibility refers to the ability of a component to monitor or mediate the interaction
between two components.
6. Portability: Portability represents the each with which a system can be moved from one
deployed location to other. portability of components by moving program code with the data;
7. Reliability: An architecture style can improve reliability by avoiding single points of failure,
using failover mechanisms, and be relying on monitoring features that can dynamically
anticipate and respond to failure conditions.
What is API?
An Application Programming Interface (API) establishes a connection between computers or
between computer programs (applications) by providing readily available codes and information
pipelines. It is a type of software interface that acts as a mediator among other pieces of software
to streamline the interaction with one other.
Step 3: Click on File menu -> New -> Spring Starter Project ->
If the Spring Starter Project is not enlisted, then click on Other at the bottom of the
menu. A dialog box appears on the screen. Type Spring Starter Project in
the Wizards text box and click on the Next button.
Step 4: provide the name, group, and package of the project. We have provided:
Name: restful-web-services
Group: [Link]
Package: [Link]
Step 5: Choose the Spring Boot Version 2.1.8 and add Spring Web MVC, Spring Boot
DevTools, JPA, and H2 dependencies in the [Link].
Step 6: We can see the project structure in the project explorer window.
Step 7: Now open the [Link] file and Run the file as Java
Application.
Step 2: Whenever we create a web service, we need to define two things Get method
and the URI. Now create the helloWorld() method which returns the string "Hello
World." If we want to tell the spring MVC that it is going to handle the REST request, we
have to add @RestController annotation. Now it becomes a rest controller which can
handle the Rest request.
package [Link];
import [Link];
import [Link];
//Controller
@RestController
public class HelloWorldController
{
//using get method and hello-world as URI
@GetMapping(path="/hello-world")
public String helloWorld()
{
return "Hello World";
}
}
Step 3: Run the RestfulWebServiceApplication. It displays the string Hello World on the
browser.
[Link]
package [Link];
import [Link];
import [Link];
//Controller
@RestController
public class HelloWorldController
{
//using get method and hello-world URI
@GetMapping(path="/hello-world")
public String helloWorld()
{
return "Hello World";
}
@GetMapping(path="/hello-world-bean")
public HelloWorldBean helloWorldBean()
{
return new HelloWorldBean("Hello World"); //constructor of HelloWorldBean
}
}
Right-click -> Source -> Generate Getters and Setters -> check the box -> Ok
package [Link];
public class HelloWorldBean
{
public String message;
//constructor of HelloWorldBean
Output:
Week 9
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
This will also include the SecurityAutoConfiguration class containing the initial/default security
configuration.
By default, the Authentication gets enabled for the Application. Also, content negotiation is used
to determine if basic or formLogin should be used.
[Link]
import [Link];
import [Link];
import [Link];
@SpringBootApplication
@EnableWebSecurity
public class SpringBasicSecurityApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}
Create Package
Name: [Link]
Create Class
Name: ApplicationController
package [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/auth")
public class ApplicationController {
@GetMapping("/getmsg")
public String greeting()
{
return "Spring Security Example";
}
}
[Link] File
[Link]=niranjan
[Link]=murthy
[Link]=8090
JUnit Tutorials
Testing: Testing is the process of checking an application that it is working as expected. In other
words testing is a process of verification and validation.
Unit testing: Unit testing is the testing of an individual unit (class/method) or group of related
units
JUnit: JUnit is an open-source unit testing framework for java programmers. It is only used for
unit testing. Integration testing is done by TestNG.
Assert class:
JUnit provides the Assert class to check the certain conditions. Assert class methods compare the
output value to the expected value.
Commonly used methods of Assert class:
1. assertTrue(boolean condition): It assert that the specified boolean condition is true.
2. assertFalse(boolean condition): It assert that the specified boolean condition is false
3. assertNull(Object obj): It assert that the specified object is null.
4. assertNotNull(Object obj): It assert that the specified object is not null.
5. assertEquals(Object expected, Object actual): It assert that two objects are equal.
6. assertSame(Object expected, Object actual): It assert that two objects refer to the same
object.
package [Link];
import static [Link];
import static [Link];
import static [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootTest
class SpringbootFirstAppApplicationTests {
@Autowired
UserRepository userRepo;
@Test
public void testCreate()
{
User u=new User();
[Link](3L);
[Link]("Kavya");
[Link]("shree");
[Link](u);
assertNotNull([Link](902L).get());
}
@Test
public void testReadAll()
{
List<User> list=[Link]();
assertThat(list).size().isGreaterThan(0);
}
@Test
public void testUpdate()
{
User u=[Link](902L).get();
[Link]("Murthy");
[Link](u);
assertNotEquals("Niranjan",[Link](902L).get().getFirstname());
}
@Test
public void testDelete()
{
[Link](852L);
assertThat([Link](852L)).isFalse();
}
}
Introduction NoSQL
A database Management System provides the mechanism to store and retrieve the data. There
are different kinds of database Management Systems:
1. RDBMS (Relational Database Management Systems)
2. OLAP (Online Analytical Processing)
3. NoSQL (Not only SQL)
NoSql
• NoSQL database stands for “Not Only SQL” or “Not SQL.”
• NoSQL Database is a non-relational Data Management System that does not require a
fixed schema.
• It avoids joins, and is easy to scale. The major purpose of using a NoSQL database is
for distributed data stores with huge data storage needs.
• NoSQL is used for Big data and real-time web apps. For example, companies like
Twitter, Face book and Google collect terabytes of user data every single day.
• NoSQL can store structured, semi-structured, unstructured and polymorphic data
Brief History:
• 1998- Carlo Strozzi use the term NoSQL for his lightweight, open-source relational
database
• 2000- Graph database Neo4j is launched
• 2004- Google BigTable is launched
• 2005- CouchDB is launched
• 2007- The research paper on Amazon Dynamo is released
• 2008- Facebooks open sources the Cassandra project
• 2009- The term NoSQL was reintroduced
Features of NoSQL
Non-relational
• NoSQL databases never follow the relational model
• Never provide tables with flat fixed-column records
• Work with self-contained aggregates
• Doesn’t require object-relational mapping and data normalization
• No complex features like query languages, query planners, referential integrity joins,
ACID
Schema-free
• NoSQL databases are either schema-free or have relaxed schemas
• Do not require any sort of definition of the schema of the data
• Offers heterogeneous structures of data in the same domain
Simple API
• Offers easy to use interfaces for storage and querying data provided
• APIs allow low-level data manipulation & selection methods
• Text-based protocols mostly used with HTTP REST with JSON
• Mostly used no standard based NoSQL query language
• Web-enabled databases running as internet-facing services
Distributed
• Multiple NoSQL databases can be executed in a distributed fashion
• Offers auto-scaling and fail-over capabilities
• Often ACID concept can be sacrificed for scalability and throughput
• Only providing eventual consistency
2. Column-oriented Graph
• They store data in tables, rows, and dynamic columns. Here each row doesn’t need to
have the same columns.
• These were created to store and process very large amounts of data distributed over many
machines.
3. Graphs based
• A graph type database stores entities as well the relations amongst those entities. The
entity is stored as a node with the relationship as edges. An edge gives a relationship
between nodes. Every node and edge has a unique identifier.
4. Document-oriented
• Document-Oriented NoSQL DB stores and retrieves data as a key value pair but the value
part is stored as a document.
• The document is stored in JSON or XML formats. The value is understood by the DB
and can be queried.
Benefits
There are many advantages of working with NoSQL databases such as MongoDB and
Cassandra. The main advantages are high scalability and high availability.
1. High scalability – NoSQL databases use sharding(dividing a larger part into smaller parts)
for horizontal scaling. Partitioning of data and placing it on multiple machines in such a
way that the order of the data is preserved is sharding. Vertical scaling means adding more
resources to the existing machine whereas horizontal scaling means adding more machines
to handle the data. Vertical scaling is not that easy to implement but horizontal scaling is
easy to implement. Examples of horizontal scaling databases are MongoDB, Cassandra,
etc. NoSQL can handle a huge amount of data because of scalability, as the data grows
NoSQL scale itself to handle that data in an efficient manner.
2. High availability – Auto replication feature in NoSQL databases makes it highly available
because in case of any failure data replicates itself to the previous consistent state.
Cap Theorm
The CAP theorem is a belief from theoretical computer science about distributed data
stores that claims, in the event of a network failure on a distributed database, it is possible to
provide either consistency or availability—but not both.
• Consistency:
The data should remain consistent even after the execution of an operation. This means once data
is written, any future read request should contain that data. For example, after updating the order
status, all the clients should be able to see the same data.
• Availability:
The database should always be available and responsive. It should not have any downtime.
• Partition Tolerance:
Partition Tolerance means that the system should continue to function even if the communication
among the servers is not stable. For example, the servers can be partitioned into multiple groups
which may not communicate with each other. Here, if part of the database is unavailable, other
parts are always unaffected.
Mongo DB
• MongoDB is a document-oriented NoSQL database used for high volume data storage.
• Instead of using tables and rows, MongoDB makes use of collections and documents.
• Documents consist of key-value pairs which are the basic unit of data in MongoDB.
• Collections contain sets of documents and function which is the equivalent of relational
database tables.
MongoDB Features
• MongoDB provides high performance. Most of the operations in the MongoDB are
faster compared to relational databases.
• MongoDB provides auto replication feature that allows you to quickly recover data in
case of a failure.
• Horizontal scaling is possible in MongoDB because of sharing. Sharding is partitioning
of data and placing it on multiple machines in such a way that the order of the data is
preserved.
• Vertical scaling means adding more resources to the existing machine.
• Load balancing: horizontal scaling allows MongoDB to balance the load.
• High Availability: Auto Replication improves the availability of MongoDB database.
• Indexing: Index is a single field within the document. Indexes are used to quickly locate
data without having to search every document.
• Normalized data model: In this model, you can refer the sub documents in the original
document, using references.
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Date_Of_Birth: "1995-09-26"
}
Address:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
city: "Mysore"
}
Install mongosh
• Visit [Link] and click on Product menu -> Tools -> Compass, then click on
Download.
• This will take you to a page where you can select a version, platform, and package to
download. Zip file will be downloaded.
• Extract the file.
• Open mongosh folder, goto bin, double click on mongosh, press enter
• Type show dbs
jsspn>
MongoDB's data types allow us to store data more efficiently while simultaneously performing
very efficient and robust queries.
2. Integer: Numeric values are stored using the integer data type. Depending on the server, it
can store 32-bit or 64-bit numbers.
3. Double: Numeric numbers containing 8 bytes floating-point are stored using the double data
type.
4. Boolean: Boolean (true or false) values are stored with the boolean data type
5. Array: We can store several values in a single key of the document with an array data type.
6. Object : An embedded document is a key-value pair that is put inside another document.
Embedded documents are stored using the object data type.
7. Date : The current date or time is stored in the ‘Date’ data type. The returning date
can be done in a variety of ways; either a string or a date object. There are three
strategies that can be used in this situation.
8. Timestamp : The term "Timestamp" refers to a set of characters used to describe the date
and time of an occurrence. The timestamp data type is commonly used to track the creation,
editing, and updating of documents. Such characters are stored in the timestamp data type. To
construct a timestamp, use the new Timestamp().
9. Null: The NULL data type is used to represent a value of zero or no value, as the name
implies.
10. Binary: This data type is used in fields to hold binary data.
"_id": "1",
"product_code": "1234-ABCD",
"product_name": "TV",
"product_price": 49999.99,.
"product_dimensions": {
"product_width": 75,
},
"mfd_date": ISODate("2022-04-10T12:45:42"),
"product_availability": true,
"product_picture":BinData(1, "rk56tyvbu5677ghugf456.")
• Comparison
• Logical
• Element
• Evaluation
• Geospatial
• Array
• Bitwise
• Comments
Comparison Operators
MongoDB comparison operators can be used to compare values in a document. The
following table contains the common comparison operators.
Operator Description
$ne Matches values that are not equal to the given value.
Logical Operators
MongoDB logical operators can be used to filter data based on given conditions. These operators
provide a way to combine multiple conditions. Each operator equates the given condition to a
true or false value.
Operator Description
Joins two or more queries with a logical AND and returns the documents
$and that match all the conditions.
Join two or more queries with a logical OR and return the documents
$or that match either query.
The opposite of the OR operator. The logical NOR operator will join
two or more queries and return documents that do not match the given
$nor query conditions.
$not Returns the documents that do not match the given query expression.
Array Operators
MongoDB array operators are designed to query documents with arrays. Here are the
array operators provided by MongoDB.
Operator Description
Week 10
Create and Drop database
MongoDB use DATABASE_NAME is used to create database. The command will create a new
database if it doesn't exist, otherwise it will return the existing database.
Syntax: use DATABASE_NAME
>use mydb
switched to db mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
>show collections
mycollection
[Link]
Creating a Table.
[Link]("student")
{ ok: 1 }
show tables
student
insert() Method
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
Syntax: db.COLLECTION_NAME.insert(document)
[Link]({"id":1,"name":"chandru","mark":300})
[Link]([{"id":1,"name":"chandru","mark":300},
{"id":2,"name":"suman","mark":290}])
Update.
[Link]({"name":"chandru"},{$set:{"name":"sekar",id:5}})
[Link]({"name":"sekar"})
Indexing
[Link]({"name":1})
'name_1'
equal.
[Link]({name:{$eq:"chandru"}})
GreaterThan.
[Link]({mark:{$gt:300}})
LessThen.
[Link]({mark:{$lt:400}})
Sort
[Link]({},{id:0}).sort({"name":1})
Count.
[Link]()
[Link]({"name":"chandru"})
Limit: limit() method limits the number of records or documents that you want.
[Link]().limit(2)
Cursor
When the [Link] () function is used to search for documents in the collection, the
result returns a pointer to the collection of documents returned which is called a cursor.
By default, the cursor will be iterated automatically when the result of the query is returned.
Indexing
• The index stores the value of a specific field or set of fields, ordered by the value of the
field as specified in the index.
>[Link]({"title":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
In createIndex() method you can pass multiple fields, to create index on multiple fields.
>[Link]({"title":1,"description":-1})
You can also specify the name of the index directly as:
dropIndex("name_of_the_index")
> [Link]({"title":1})
{
"ok" : 0,
"errmsg" : "can't find index with key: { title: 1.0 }",
"code" : 27,
"codeName" : "IndexNotFound"
}
The dropIndexes() method
This method deletes multiple (specified) indexes on a collection.
Syntax: db.COLLECTION_NAME.dropIndexes()
> [Link]({"title":1,"description":-1})
>[Link]({"title":1,"description":-1})
{ "nIndexesWas" : 2, "ok" : 1 }
{
_id: ObjectId(7df78ad8902c)
"$likes"}}}])
Perform CRUD Operations on MongoDB through REST API using Spring Boot Starter
Data MongoDB
Step 3: Create 3 packages and create some classes and interfaces inside these packages
• entity
• repository
• controller
package [Link];
import [Link];
import [Link];
public interface BookRepo
extends MongoRepository<Book, Integer> {
}
Step 6: Inside the controller package. Inside the package create one class named
as BookController
package [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
@RestController
public class BookController {
@Autowired
private BookRepo repo;
@PostMapping("/addBook")
public String saveBook(@RequestBody Book book){
[Link](book);
return "Added Successfully";
}
@GetMapping("/findAllBooks")
public List<Book> getBooks() {
return [Link]();
}
@DeleteMapping("/delete/{id}")
public String deleteBook(@PathVariable int id){
[Link](id);
return "Deleted Successfully";
}
}
Step 7: Below is the code for the [Link] file
[Link]
[Link]=localhost
[Link]=27017
[Link]=jss
Week 11
Application Testing
What is Application Testing?
Application Testing is defined as a software testing type conducted through scripts with the
motive of finding errors in software. It deals with tests for the entire application.
It helps to enhance the quality of your applications while reducing costs, maximizing ROI, and
saving development time.
Manual testing is testing of the software where tests are executed manually by a QA Analyst. It
is performed to discover bugs in software under development.
Automation Testing uses automation tools In manual testing, test cases are executed
Definition
to execute test cases. by a human tester and software.
Not cost effective for low volume Not cost effective for high volume
Cost-effective
regression regression.
With automation testing, all stakeholders Manual Tests are usually recorded in an
Test Report
can login into the automation system and Excel or Word, and test results are not
Visibility
check test execution results readily/ readily available.
Automated Tests have zero risks of Manual Testing has a higher risk of
Deadlines
missing out a pre-decided test. missing out the pre-decided test deadline.
There are various testing tools for Application Testing. Selection of tools depends on what type
of testing you want to perform. For different platform different tools are recommended.
Application testing tools ensure performance, usability and functionality of applications across a
variety of devices.
• Selenium
• IBM Rational Robot
• RFT (Rational Functional Tester)
• Load Runner ( HP Performance Tester)
• Apache Jmeter
FUNCTIONAL TESTING
Functional testing is a type of software testing that validates the software system against the
functional requirements/specifications. The purpose of Functional tests is to test each function of
the software application, by providing appropriate input, verifying the output against the
Functional requirements.
• Check all the GUI elements for size, position, width, length, and acceptance of characters
or numbers. For instance, you must be able to provide inputs to the input fields.
• Check you can execute the intended functionality of the application using the GUI
• Check Error Messages are displayed correctly
• Check for Clear demarcation of different sections on screen
• Check Font used in an application is readable
• Check the alignment of the text is proper
• Check the Color of the font and warning messages is aesthetically pleasing
• Check that the images have good clarity
• Check that the images are properly aligned
• Check the positioning of GUI elements for different screen resolution.
System testing
System Testing is a level of testing that validates the complete and fully integrated software
product. The purpose of a system test is to evaluate the end-to-end system specifications.
Integrate the work of each group and carry out integration testing
Acceptance testing
Acceptance Testing is the last phase of software testing performed after System Testing and
before making the system available for actual use.
User Acceptance Testing (UAT) is a type of testing performed by the end user or the client to
verify/accept the software system before moving the software application to the production
environment. UAT is done in the final phase of testing after functional, integration and system
testing is done.
UAT is performed by –
Client
End users
Bug and issue tracking tools help software teams find, record, and track bugs in their software.
It's critical that everyone on your team is able to find and record bugs, and even more important,
assign them to the right team members at the right time.
Deployment process
• Software deployment includes all of the steps, processes, and activities that are required
to make a software system or update available to its intended users.
• Today, most IT organizations and software developers deploy software updates, patches
and new applications with a combination of manual and automated processes.
• Basic
• Multi-service
• Rolling
• Blue Green Deployment
• Canary
• A/B Testing
Manual deployment
Manual configuration is intended for advanced users when more control of the application server
environment is required. When the configuration utility is run with the manual deployment mode
selected, it makes necessary changes to the database, but your application server is not changed.
Deployable application files, installation scripts, and properties files are generated in
the <repository installation directory>/toDeploy/<timestamp> directory.
Automated deployment
Deployment automation is the use of automated processes to move your software between
testing and production environments. This process is both reliable and repeatable across
the software delivery lifecycle (SDLC).
• Jenkins
• Visual Studio
• AWS CodeDeploy
• Ensure that it runs every time a change is checked into source control.
1. Bamboo
Key Features:
2. TeamCity
Key Features:
3. AWS CodeDeploy
Key Features:
4. Octopus Deploy
Key Features:
5. ElectricFlow
Key Features:
6. PDQ Deploy
Key Features:
• Customize installs
• Installs to multiple computers simultaneously
• Real-time status monitoring
7. Ansible Tower
Key Features:
8. Chef
Key Features:
9. Codeship
Key Features:
• Docker support
• Parallel deployments and testing
• Debugging via SSH access and command line interface
10. AppVeyor
Key Features:
1. Argonaut
Deploy apps and infrastructure on your cloud in minutes. Support for custom and third-party app
deployments on Kubernetes and Lambda environments.
2. Flosum
Flosum is a native DevOps solution that handles the development lifecycle including merging
components, version control, continuous deployments, static code analysis, user story
management, and regression testing. Flosum works together with Salesforce to identify changes
in a particular component.
3. Codefresh
Codefresh is an enterprise continuous delivery platform for cloud-native applications. It
automates GitOps workflows and advanced deployments such as Canary and Blue/Green.
4. Launch Darkly
LaunchDarkly is a feature management application that enables teams to deploy code at any
time, even if a feature isn’t ready to be released to all users.
5. Harness
Harness Continuous Delivery is a software delivery solution that automatically deploys, verifies,
and rolls back artifacts. You can leverage automated canary and blue-green deployments for
faster, safer, and more efficient rollouts.
6. Juju
Juju is an open source application and service modeling tool from Ubuntu that helps you deploy,
manage and scale your applications on any cloud. With Juju, different authors are able to create
service formulas, called charms, independently, and make those services coordinate their
communication and configuration through a simple protocol. Juju can also be used together with
Orchestra for physical deployments.
7. Rundeck
Rundeck is an open source operations management platform that helps to automate routine
operational procedures in data center or cloud environments. It enables you to run tasks on any
number of nodes from a web-based or command-line interface.
Refer : [Link]
Continuous deployment
Continuous deployment is a strategy for software releases wherein any code commit that passes
the automated testing phase is automatically released into the production environment, making
changes that are visible to the software's users.
Continuous deployment eliminates the human safeguards against unproven code in live software.
It should only be implemented when the development and IT teams rigorously adhere to
production-ready development practices and thorough testing, and when they apply
sophisticated, real-time monitoring in production to discover any issues with new releases.
Static analysis is a method of debugging that is done by automatically examining the source code
without having to execute the program. This provides developers with an understanding of their
code base and helps ensure that it is compliant, safe, and secure.
When Is Static Code Analysis Performed?
Static code analysis is performed early in development, before software testing begins. For
organizations practicing DevOps, static code analysis takes place during the “Create” phase.
Containers
A container is a standard unit of software that packages up code and all its dependencies so the
application runs quickly and reliably from one computing environment to another.
Why containers?
Containers require less system resources than traditional or hardware virtual machine
environments because they don't include operating system images. Applications running in
containers can be deployed easily to multiple different operating systems and hardware
platforms.
What is a docker?
Docker is an open source platform for building, deploying, and managing containerized
applications.
Docker uses a client-server architecture. The Docker client talks to the Docker daemon, which
does the heavy lifting of building, running, and distributing your Docker containers. The Docker
client and daemon can run on the same system, or you can connect a Docker client to a remote
Docker daemon.
Components of docker
- Docker container
Docker containers are the live, running instances of Docker images. While Docker images are
read-only files, containers are life, ephemeral, executable content. Users can interact with them,
and administrators can adjust their settings and conditions using Docker commands.
- Docker client
Docker client is an application for Mac or Windows that includes Docker Engine, Docker CLI
client, Docker Compose, Kubernetes, and others. It also includes access to Docker Hub.
- Docker daemon
Docker daemon is a service that creates and manages Docker images, using the commands from
the client. Essentially Docker daemon serves as the control center of your Docker
implementation. The server on which Docker daemon runs is called the Docker host.
-Docker image
Docker images contain executable application source code as well as all the tools, libraries, and
dependencies that the application code needs to run as a container. When you run the Docker
image, it becomes one instance (or multiple instances) of the container.
- Docker registry
A Docker registry is a scalable open-source storage and distribution system for Docker images.
The registry enables you to track image versions in repositories, using tagging for identification.
This is accomplished using git, a version control tool.
Click on Next.
For the second screen, choose a location where to store your Docker files, and click on Next.
Click on Next.
For the additional tasks, you can let the default options and click on Next.
After a short while, your installation should complete. Leave the checkbox checked in order to
see the shortcuts created by Docker.
$ docker version
Docker file
Every Docker container starts with a simple text file containing instructions for how to build the
Docker container image. DockerFile automates the process of Docker image creation. It’s
essentially a list of command-line interface (CLI) instructions that Docker Engine will run in
order to assemble the image. The list of Docker commands is huge, but standardized: Docker
operations work the same regardless of contents, infrastructure, or other environment variables.
Docker image
Docker images contain executable application source code as well as all the tools, libraries, and
dependencies that the application code needs to run as a container. When you run the Docker
image, it becomes one instance (or multiple instances) of the container.
ADD – Defines files to copy from the Host file system onto the Container
Refer : [Link]
The Docker create command will create a new container for us from the command line:
You can also tag the image as it is created by adding another argument to the end of the command
like this:
Refer : [Link]
To run a container, the only thing you need to include in the command is the image on which it is
based:
As an example, we used a Dockerfile to create a sample Docker image with the task to echo the
message Hello World. For us, the image has the ID e98b6ec72f51. Your image name will differ
depending on the container you want to run.
Refer : [Link]
Week12
Container
Containers are lightweight, executable application components that combine application source
code with all the operating system (OS) libraries and dependencies required to run the code in
any environment.
Orchestration
Orchestration is the automated configuration, management, and coordination of computer
systems, applications, and services. Orchestration helps IT to more easily manage complex tasks
and workflows.
Container orchestration
• Container orchestration automates the provisioning, deployment, networking, scaling,
availability, and lifecycle management of containers.
• Kubernetes is the most popular container orchestration platform, and most leading public
cloud providers - including Amazon Web Services (AWS), Google Cloud Platform, IBM
Cloud and Microsoft Azure - offer managed Kubernetes services.
• Other container orchestration tools include Docker Swarm and Apache Mesos.
Orchestration tools
1. Kubernetes
2. Openshift
3. Nomad
[Link] Swarm
5. Docker Compose
6. MiniKube
7. Marathon
8. Cloudify
Kubernetes
Kubernetes — also known as “k8s” or “kube” — is a container orchestration platform for
scheduling and automating the deployment, management, and scaling of containerized
applications.
Why Kubernetes?
• Service discovery and load balancing: If traffic to a container is high, Kubernetes is
able to load balance and distribute the network traffic so that the deployment is stable.
• Automated rollouts and rollbacks: it can change the actual state to the desired state at
a controlled rate. For example, you can automate Kubernetes to create new containers for
your deployment, remove existing containers and adopt all their resources to the new
container.
• Automatic bin packing: You provide Kubernetes with a cluster of nodes that it can use
to run containerized tasks. You tell Kubernetes how much CPU and memory (RAM) each
container needs. Kubernetes can fit containers onto your nodes to make the best use of
your resources.
• Self-healing: Kubernetes restarts containers that fail, replaces containers, kills containers
that don't respond to your user-defined health check, and doesn't advertise them to clients
until they are ready to serve.
• Secret and configuration management: Kubernetes lets you store and manage sensitive
information, such as passwords, OAuth tokens, and SSH keys. You can deploy and
update secrets and application configuration without rebuilding your container images,
and without exposing secrets in your stack configuration.
Kubernetes configuration
- Deployment
- Service
- Load balancer/ingress
Deployment strategies:
A Deployment strategy defines how to create, upgrade, or downgrade different versions of
Kubernetes applications.
Blue green deployment :
Canary Deployment
Disaster recovery
Disaster recovery is the process by which an organization anticipates and addresses technology-
related disasters.
Kubernetes disaster recovery can be broken down into two phases: backup and recovery.
Backup is the process of preserving data before any disaster strikes, while recovery entails
getting back up after one has occurred.
JavaScript Variables:
In a programming language, variables are used to
JavaScript uses the keywords var, and const to declare variables. An equal sign is used to
assign values to variables.
JavaScript variables:
4 ways to Declare a JavaScript Variable:
Using var
Using let
Using const
Using nothing
JavaScript is a case sensitive
All JavaScript identifies are case sensitive.
The variables lastName and lastname, are two different variables:
JavaScript Comments:
Not all JavaScript statements are “executed”.
Comments are ignored, and will not be executed:
Single line comment is begins with //
Multiline Comment is between /* */
Code after double slashes // or between /* and */ is treated as a comment.
JavaScript Operators:
JavaScript uses arithmetic operator (+ _ * /) to compute values.
JavaScript Function:
A JavaScript Function is a block of code designed to perform a particular task. A JavaScript
Function is executed when “something” invokes it (calls it).
Why functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
JavaScript if, else, and else if
Conditional statements are used to perform different actions based on different conditions.
Conditional statements:
Very often when you write code, you want to perform different actions for decisions.
JavaScript Switch Statement:
The switch statement is used to perform different actions based on different conditions.
JavaScript JSON (JavaScript object Notation):
JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.
What is JSON?
JSON stands for JavaScript object notation
JSON is a lightweight data interchange format.
JSON is language independent
JSON is “self-describing” and easy to understand.
The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is
text only. Code for reading and generating JSON data can be written in any programming
language.\
JSON example
This example is a JSON string:
„{“name”:”john”,”age”:30,”car”:null‟}
It defines an object with 3 properties:
Name, age, car.
JavaScript Objects:
A JavaScript object is a collection of named values In JavaScript, objects are king. If you
understand objects you understand JavaScript.
IN JavaScript. Almost “everything” is an object.
Booleans can be objects (if defined with The new keyword)
Numbers can be objects(if defined with the key word)
Data are always objects.
Math are always objects.
Regular Expressions are always object.
Arrays are always objects.
Functions are always object.
Objects are always objects.
Object properties:
The named values, in JavaScript object
Property value
firstName kim
lastName Namjoon
age 28
eyeColor black
Object Methods:
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property Value
firstName kim
lastName Namjoon
age 28
eyeColor black
fullName function() {return [Link] + “” + [Link];}
JavaScript objects are containers for named values, called properties and methods.
JavaScript methods:
JavaScript methods are actions that can be performed on objects. A JavaScript method is a
property containing a function definition.
Property value
firstName kim
age 24
eyeColor blue
fullName function() {return [Link]+ “ “ +[Link];}
Methods are functions stored as object properties.
JavaScript Object Constructors:
Objects of the same type are created by calling the constructor function with the new
keyword.
The way to create an “object type”, is to use an object constructor function.
JavaScript Properties:
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties:
The syntax for accessing the property of an object is:
[Link] //[Link]
or
objectName[“property”] //person[“age”]
or
objectName[expression] //x=”age”;person[x]
prototype properties:
JavaScript objects inherit the properties of their
The delete keyword does not delete inherited properties. But if you delete a prototype
property. It will effect all objects inherited from the prototype.
JavaScript Sets:
A JavaScript set is a collection of unique values.
Each value can only occur once in a set.
A set can hold any value of any data type.
Set Methods:
Method Description
New set() Creates a new set
Add() Adds a new element to the set
Delete() removes an element of an set
Has() returns a true if a value exists
Clear() removes all element from a set
forEach() Invokes a callback for each element
values() Returns an Iterator with all the values in a set.
Keys() same as values()
Entries() Returns an Iterator with the [value, value] pairs from a set.
JavaScript Maps:
A Maps holds key-value pairs where the keys can be any data type.
A Map remembers the original insertion order of the keys.
A Maps has a property that represents the size of the map.
Map Methods:
Method Description
New map() Creates a new Map object
Set() Sets the value for a key in a map
Get() gets the value for a key in a map
Clear() removes all the elements from a map
Delete() removes a map element specified by a key
Has() returns true if a key exists in a map
forEach() invokes a callback for each key/value pair in a map.
Entries() returns an iterator object with the [key, value] pairs in a map.
Keys () returns an iterator object with the keys in a map
Values () returns an iterator object of the values in a map.
React:
React is JavaScript front-end, library sdevelopment by fbJsx JavaScript xmu.
React is a JavaScript library for building user interfaces.
React is used to build single-page applications.
React allows us to create reusable UI components.
What is React?
React sometimes referred to as a front-end JavaScript framework, is a JavaScript library
created by facebook.
React is tool for building component.
Setting up a react environment:
If you have npx and [Link] installed, you can create a React application by using
create-react-app.
If you‟ve previously installed create-react-app globally, it is recommended that you
install the package to ensure npx always uses the latest version of create-react-app.
To uninstall, run this command: npm uninstalling create>react-app.
Run this command to create a react application named ny-react-app.
Npx create-react-app my-react-app
Installing [Link] using webpack and babel
1. Please click on “install” button download Node JS platform version 0.12.
2. Please double click on “node.v0”.
3. Choose your required location to install.
4. Choose default values and click on “install” button.
5. Open [Link] platform home in your explores.
Run
To uninstall , run this command npm uninstalling create -react-app.
Run this command to create a react application named my-react-app
Run this command to move to the my-react-app directory.
Cd my-react-app
What is JSX?
JSX stands for JavaScript XML(xml is extention of HTML).
JSX allows to write HTML in react.
Also it makes easier to write and add HTML in react.
Example: create Element {---}
Append Child{----}
Expressions in JSX:
Expressions in JSX
The expressions can be react variable or property are any other valid JavaScript express.
Ex: const myElement = <header> react is {5+5} times better with JSX.</header>
Attribute class = className
A class attribute is a much used in HTML attribute, but since JSX is rendered JavaScript and
the class keyword is reserved word in JavaScript.
Ex: const myElement=<h1 className = “myclass”>Hello world</h1>;
React components:
Components are independent and reusable bits of code. They serve the same purpose as
javascript functions, but work in isolation and return in html.
React components they are two types:
1. Class components
2. Function components.
1. A class components includes the extents [Link] statements. This
statements create an inheritance to react component, and gives your components
excess to react component function.
ex: class car extends [Link] {
render() { return <h1> hi, I am not a car!</h1>;
}
A function components also returns html, and behaves much the same way as a class
components but function components can be return using much function less code, are
eiser to understand also it is a powerfull.
Ex:
Function car(){
Return <h1>hi, I am a car! </h1>;
}
Rendering a component:
To use this component in your application, use similar syntax as normal html. <car>
</car>
Display the car component in the root element “root” .
Ex:
Const root=[Link] ([Link](“root”));
[Link](<car/>);
Props: props are like function arguments, and you send them into the component as
attributes.
Ex:
Function car(prpos) {return<h2> I am a {[Link]} car!</h2>;
Const root =[Link]
([Link](„root‟));
Root render(<car color = “red” />;
React state:
The state object is where you store property values that belongs to the component.
Creating the state object is initialized in the constructor.
Ex:
Class car extends [Link]{
Constructor (props){
Super(props)
[Link]={brand: “BMW”};
}
Render(){
Return(
<div>
<h1> my car</h1>
</div>);
}
}
React list:
In react list, you will render list in some type of loop.
The JavaScript map array method is generally the prepared method.
Ex: function car(props){
Return<li> I am a {[Link]}</li>;
}
Function garage(){
Const cars=[„ford‟, „bmw‟, „audi‟];
Return(
<>
<h1> who lives in my garage?</h1>
<ul>
{[Link]((car)=><car brand={car}/>}
</ul>
<i>);
}
Const root=[Link]([Link](„root‟));
[Link](<garage/>);
React keys: react keys allows, react to keep track of element this way, if an a item is update
or removed only that item will be rerender instead of the entire list.
Ex: function car(props){
Return<li> I am a {[Link]}</li>;
}
function garage(){
Const cars={id:1,brand:‟ford‟}
{id:2,brand:‟bmw‟}
{id:3,brand:‟audi‟}
Return(
<>
<h1> who lives in my garage?</h1>
<ul>
{[Link]((car)=><car brand={car, id, brand={[Link]}/>}
</ul>
<i>);
}
Const root=[Link]([Link](„root‟));
[Link](<garage/>);
Example 1:
Import React from „react‟;
Import ReactDOM from „react-dom/client‟;
function MyForm() {
return (
<form>
<label>Enter your name:
<input type=”text”/>
</label>
</form>
)
What is HOOK?
Hooks allow us to “hook” into React features such as state and lifecycle methods.
Hook rules:
There are 3 rules for hooks:
Hooks can only be called inside React function components.
Hooks can only be called at the top level of a component.
Hooks cannot be conditional.
React useState Hook:
The React useState Hook allows us to track state in a function component.
Import { useState } from “react”;
Import ReactDOM from “react-dom/client”;
Function FavoriteColor() {
Const [color, setColor] = useState(“red”);
Return (
<>
<h1>My favorite color is {color}! </h1>
<button
type=”button”
onClick= {() = >setColor (“blue”)}
>Blue </button>
</>
)
}
Const root = [Link]([Link](„root‟));
[Link](<FavoriteColor />);
Example2:
Import React, { useState } from “react”;
Import ReactDOM from “react-dom/client”;
function FavoriteColor(){
const [color, setColor] = useState(“red”);
return(
<>
<h1> MY favorite color is {color}! </h1>
<button
Type=”button”
onClick={() => setColor(“blue”)}
>Blue</button>
Type=”button”
onClick={() =>setColor(“red”)}
>Red</button>
<button
Type=”button”
onClick={() => setColor(“pink”)}
>pink</button>
<button
Type=”button”
onClick={() => setColor(“green”)}
>green</button>
</>
);
}
Const root=
[Link]([Link](„root‟));
[Link](<FavoriteColor />;
Type Script:
Type script is a syntactic super set of JavaScript which adds static typing.
Why should I use typescript?
JavaScript is a loosely typed language. It can be difficult to understand what types of data are
being passed around in JavaScript.
In JavaScript, function parameters and variables do not have any information. So developers
needs to look at documentation, or guess based on the implementation.
TypeScript compiler: TypeScript is transpiled into JavaScript using a compiler.
TypeScript being converted into JavaScript means turns anywhere that JavaScript runs.
(intel j ide app)
Installing the compiler: TypeScript is a installed compiler which can be installed through
notepad++ or NPM.
For running the TypeScript program [Link] to run typescript program. Suppose we use
nodejs we use npm.
Basic type or simple types (primitive): types script supports simple type or basic type
There are three main type of basic Type: or primitive
1. Boolean
2. String (typescript, rocks)
3. Number
TypeScript function: typescript has a specific syntax for typing function parameters and
a return values.
Example 6: function gettime(): number{
return new Date().gettime();
}
[Link](gettime());
What is an API?
Application programming interface (API) is a software interface that allows two
applications to interact with each other without any user intervention. API is a collection
of software functions and procedures. In simple terms, API means a software code that
can be accessed or executed. API is defined as a code that helps two different software‟s
to communicate and exchange data with each other.
Application programming interface
Try{
[Link](showPostion);
} catch {
[Link]=err;
}
}
Function showPostion (postion){
[Link] =”Latitude: “ + [Link] + “<br>Longitude: “
+[Link];
}
</script>
</body>
</html>
Meta character attribute: HTML <meta> tag which specifies the character encoding for the
HTML document
<head>
<meta> - character set chartset=UTF-8 the character set attribute specifies the character
encoding for the HTML document.
UTF-8: Unicode transformation format, it can be used to represent any Unicode character
depending on a Unicode numeric value. For corresponding UTF-8 code is 1,2or 3byte
sequence.