UNIT-4
Introduction to JavaScript
JavaScript is a lightweight, cross-platform, single-threaded, and interpreted
compiled programming language. Bredan Eich developed JavaScript in 1995 after
Netscape handed JavaScript. It is also known as the scripting language for webpages.
It is well-known for the development of web pages, and many non-browser
environments also use it. JavaScript is a weakly typed language (dynamically typed).
JavaScript can be used for Client-side developments as well as Server-side
developments. JavaScript is both an imperative and declarative type of language.
JavaScript contains a standard library of objects, like Array, Date, and Math, and a
core set of language elements like operators, control structures, and statements.
Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an
HTML form and respond to user events such as mouse clicks, form input, and page
navigation. Useful libraries for the client side are AngularJS, ReactJS, VueJS, and
so many others.
Server-side: It supplies objects relevant to running JavaScript on a server. For if the
server-side extensions allow an application to communicate with a database, and
provide continuity of information from one invocation to another of the application,
or perform file manipulations on a server. The useful framework which is the most
famous these days is [Link].
How to Link JavaScript File in HTML ?
JavaScript can be added to HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML file by writing the code
inside the <script> tag. The <script> tag can either be placed inside the <head> or
the <body> tag according to the requirement.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>
<body>
<!-- JavaScript code can be embedded inside
head section or body section -->
<script>
[Link]("Welcome to Javascript");
</script>
</body>
</html>
External JS: We can write JavaScript code in another files having an [Link]
and then link this file inside the <head> tag of the HTML file in which we want to
add this code.
<!DOCTYPE html>
<html>
<head>
<!-- External JS linked from separate file -->
<script src="[Link]"></script>
</head>
<body>
<button me</button>
</body>
</html>
Advantages of JavaScript
1. JavaScript is a lightweight language that does not require heavy software
installations or hardware infrastructure to run.
2. JavaScript is easy to learn and implement, which is another reason why it has
become so popular among developers.
3. JavaScript is one of the most popular programming language in the world,
with millions of developers using it to build web applications and mobile apps.
4. JavaScript can be utilized for both front-end and back-end development
purposes. For back-end development, [Link] is often employed, while for
front-end development, various libraries such as AngularJS and ReactJS can
be utilized.
5. it can be used to build high-performance applications that can handle complex
calculations and operations
Disadvantages of JavaScript
1. JavaScript can be secure if used properly, but it can also pose a security risk
if not implemented correctly.
2. JavaScript can be interpreted differently by various browsers, making it
necessary to test and run the code on different platforms before publishing.
3. JavaScript's debugging tools are not as advanced as those of other
programming languages, which can make it difficult to identify and fix bugs
and errors in code.
4. In terms of speed, JavaScript is generally slower than lower-level
programming languages such as C++ or Java. This is due to JavaScript's
interpreted nature, which means that code is executed line-by-line rather than
being compiled into machine code before execution.
5. JavaScript only supports single inheritance, unlike other programming
languages that allow for multiple inheritance. This can make it more
challenging for developers to create complex data structures.
What is DOM?
DOM, or Document Object Model, is a programming interface that represents
structured documents like HTML and XML as a tree of objects. It defines how to
access, manipulate, and modify document elements using scripting languages like
JavaScript.
The DOM is a W3C (World Wide Web Consortium) standard and it defines a
standard for accessing documents.
The W3C Dom standard is divided into three different parts:
Core DOM – standard model for all document types
XML DOM – standard model for XML documents
HTML DOM – standard model for HTML documents
HTML DOM
HTML DOM is a standard object model and programming interface for HTML
documents. HTML DOM is a way to represent the webpage in a structured
hierarchical way so that it will become easier for programmers and users to glide
through the document.
With HTML DOM, we can easily access and manipulate tags, IDs, classes,
attributes, or elements of HTML using commands or methods provided by the
document object.
Using DOM JavaScript, we get access to HTML as well as CSS of the web page and
can also modify the behavior of the HTML elements.
Why is DOM Required?
HTML is used to structure the web pages and Javascript is used to add behavior to
our web pages. When an HTML file is loaded into the browser, the JavaScript can
not understand the HTML document directly. So it interprets and interacts with the
Document Object Model (DOM), which is created by the browser based on the
HTML document.
DOM is basically the representation of the same HTML document but in a tree-like
structure composed of objects. JavaScript can not understand the tags(<h1>H</h1>)
in HTML document but can understand object h1 in DOM.
JavaScript interprets DOM easily, using it as a bridge to access and manipulate the
elements. DOM Javascript allow access to each of the objects (h1, p, etc) by using
different functions.
The Document Object Model (DOM) is essential in web development for several
reasons:
Dynamic Web Pages: It allows you to create dynamic web pages. It enables the
JavaScript to access and manipulate page content, structure, and style dynamically
which gives interactive and responsive web experiences, such as updating content
without reloading the entire page or responding to user actions instantly.
Interactivity: With the DOM, you can respond to user actions (like clicks, inputs,
or scrolls) and modify the web page accordingly.
Content Updates: When you want to update the content without refreshing the
entire page, the DOM enables targeted changes making the web applications more
efficient and user-friendly.
Cross-Browser Compatibility: Different browsers may render HTML and CSS in
different ways. The DOM provides a standardized way to interact with page
elements.
Single-Page Applications (SPAs): Applications built with frameworks such as
React or Angular, heavily rely on the DOM for efficient rendering and updating of
content within a single HTML page without reloading the full page.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The term structure
model is sometimes used to describe the tree-like representation of a document.
Each branch of the tree ends in a node, and each node contains objects Event
listeners can be added to nodes and triggered on an occurrence of a given event. One
important property of DOM structure models is structural isomorphism: if any two
DOM implementations are used to create a representation of the same document,
they will create the same structure model, with precisely the same objects and
relationships.
Why DOM is called an Object Model?
Documents are modeled using objects, and the model includes not only the structure
of a document but also the behavior of a document and the objects of which it is
composed like tag elements with attributes in HTML.
Structure of DOM
JavaScript Form Validation
JavaScript Form Validation is a way to ensure that the data users enter into a form is
correct before it gets submitted. This helps ensure that things like emails, passwords,
and other important details are entered properly, making the user experience
smoother and the data more accurate.
Steps for Form Validation in JavaScript
When we validate a form in JavaScript, we typically follow these steps:
• Data Retrieval:
o The first step is to get the user’s values entered into the form fields (like
name, email, password, etc.). This is done using
[Link], which refers to the form with the name
“RegForm”.
• Data Validation:
o Name Validation: We check to make sure the name field isn’t empty
and doesn’t contain any numbers.
o Address Validation: We check that the address field isn’t empty.
o Email Validation: We make sure that the email field isn’t empty and
that it includes the “@” symbol.
o Password Validation: We ensure that the password field isn’t empty
and that the password is at least 6 characters long.
o Course Selection Validation: We check that a course has been selected
from a dropdown list.
• Error Handling:
o If any of the checks fail, an alert message is shown to the user using
[Link], telling them what’s wrong.
o The form focuses on the field that needs attention, helping the user
easily fix the error.
• Submission Control:
o If all the validation checks pass, the function returns true, meaning the
form can be submitted. If not, it returns false, stopping the form from
being submitted.
• Focus Adjustment:
o The form automatically focuses on the first field that has an error,
guiding the user to fix it.
Statements in JavaScript
In JavaScript, a statement is a piece of code that performs an action. Statements are
the building blocks of JavaScript programs and can include various types of
instructions. They can be simple or complex and can control the flow of execution
in a program.
Declaration Statements: These are used to declare variables.
let x = 10;
Declares a variable x and initializes it to 10
Types of Statements
1. Variable Declarations
var name = "Alice";
2. Expression Statements
let sum = 5 + 10; // This is an expression statement.
3. Control Flow Statements
If statement
if (age >= 18) {
[Link]("Adult");
}
Else statement
else {
[Link]("Minor");
}
Else if statement
else if (age > 60) {
[Link]("Senior");
}
Switch ststement
switch (fruit) {
case "apple":
[Link]("Apple");
break;
case "banana":
[Link]("Banana");
break;
default:
[Link]("Unknown fruit");
}
Break statement
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Exits the loop when i is 5
}
Continue Statement
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // Skips even numbers
[Link](i); // Logs only odd numbers
}
Functions in JavaScript:
Functions in JavaScript are fundamental building blocks that allow you to
encapsulate code for reuse and organization. They are blocks of code designed to
perform a particular task and can be executed when called.
Function Declaration
function add(a, b) {
return a + b; // Returns the sum of a and b
}
// Calling the function
const result = add(5, 10);
[Link](result); // Output: 15
Objects in JavaScript
An object in JavaScript is a data structure used to store related data collections. It
stores data as key-value pairs, where each key is a unique identifier for the
associated value. Objects are dynamic, which means the properties can be added,
modified, or deleted at runtime.
Example:
let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
[Link](obj);
Basic Operations on JavaScript Objects:
1. Accessing Object Properties
let obj = { name: "Sourav", age: 23 };
// Using Dot Notation
[Link]([Link]);
// Using Bracket Notation
[Link](obj["age"]);
2. Modifying Object Properties
let obj = { name: "Sourav", age: 22 };
[Link](obj);
[Link] = 23;
[Link](obj);
3. Adding Properties to an Object
let obj = { model: "Tesla" };
[Link] = "Red";
[Link](obj);
4. Removing Properties from an Object
let obj = { model: "Tesla", color: "Red" };
delete [Link];
[Link](obj);
JavaScript Arrays:
An array in JavaScript is a data structure used to store multiple values in a single
variable. It can hold various data types and allows for dynamic resizing. Elements
are accessed by their index, starting from 0.
Example
// Creating an Empty Array
let a = [];
[Link](a);
// Creating an Array and Initializing with Values
let b = [10, 20, 30];
[Link](b);
Basic Operations on JavaScript Arrays:
1. Accessing Elements of an Array
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing Array Elements
[Link](a[0]);
[Link](a[1]);
2. Accessing the First Element of an Array
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing First Array Elements
let fst = a[0];
[Link]("First Item: ", fst);
3. Accessing the Last Element of an Array
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing Last Array Elements
let lst = a[[Link] - 1];
[Link]("First Item: ", lst);
4. Modifying the Array Elements
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
[Link](a);
a[1]= "Bootstrap";
[Link](a);
5. Adding Elements to the Array
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Add Element to the end of Array
[Link]("[Link]");
// Add Element to the beginning
[Link]("Web Development");
[Link](a);
6. Array Length
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
let len = [Link];
[Link] ("Array Length: " + len);