0% found this document useful (0 votes)
5 views35 pages

3rd Unit - XML & Java Script

The document provides an overview of XML and JavaScript, highlighting XML's role in data encoding, interchange, and structure, as well as its differences from HTML. It also covers JavaScript's history, client-side and server-side applications, and its object-oriented programming features, including classes and key principles like encapsulation and inheritance. Additionally, it illustrates how XML and JavaScript can be utilized together in web development for dynamic content and data management.

Uploaded by

shravanahudali87
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views35 pages

3rd Unit - XML & Java Script

The document provides an overview of XML and JavaScript, highlighting XML's role in data encoding, interchange, and structure, as well as its differences from HTML. It also covers JavaScript's history, client-side and server-side applications, and its object-oriented programming features, including classes and key principles like encapsulation and inheritance. Additionally, it illustrates how XML and JavaScript can be utilized together in web development for dynamic content and data management.

Uploaded by

shravanahudali87
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3:XML & JavaScript

XML :Extensible Markup Language


Introduction:
Extensible Markup Language (XML) is a markup language that defines a set of rules for
encoding documents in a format that is both human-readable and machine-readable. The design
goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual
data format with strong support via Unicode for different human languages. Although the
design of XML focuses on documents, the language is widely used for the representation of
arbitrary data structures such as those used in web services.
1. XML stands for extensible Markup Language
2. XML is a markup language like HTML
3. XML is designed to store and transport data
4. XML is designed to be self-descriptive

Differences between XML and HTML


XML and HTML were designed with different goals:
 XML is designed to carry data emphasizing on what type of data it is.
 HTML is designed to display data emphasizing on how data looks
 XML tags are not predefined like HTML tags.
 HTML is a markup language whereas XML provides a framework for defining markup
languages.
 HTML is about displaying data,hence it is static whereas XML is about carrying
information,which makes it dynamic.

EXAMPLE : XML code for a note is given below

HTML code for the note is given below

<!DOCTYPE html>
<html>
<h1>Note</h1>
<body>
<p>To:RAJ
<br>
From:RAVI
</p>
<h1>Reminder</h1>
<p>Meeting at 8am</p></body></html>

1
Unit 3:XML & JavaScript

OUTPUT:

The output in both the cases is same but while using HTML we have used predefined tags like
p tag and h1 tag whereas while using XML we have used self defined tags like "To" tag and
"from" tag.
Another Example: The XML above is quite self-descriptive:
 It has sender information.
 It has receiver information.
 It has a heading.
 It has a message body.
 The tags in the example below are not defined in any XML standard. These tags are
"invented" by the author of the XML [Link] works with predefined tags like p tag,
h1 tag, [Link] in XML, the author must define both the tags and the document structure.

Significance of XML:

 Data Interchange and Interoperability: XML acts as a universal translator, allowing PDF
content to be converted into a structured, machine-readable format. This enables businesses to
extract data from fixed-layout PDFs (like invoices or reports) and share it across incompatible
software systems.

 Separation of Content and Presentation: While PDF is designed to maintain a consistent


visual appearance across all devices, XML focuses on what the data is. This distinction allows
developers to store "source" data in XML and then use style sheets (like XSLT) to generate a
PDF for final presentation.

 Accessibility and Searchability: Converting PDF to XML enhances search efficiency because
XML tags provide context for content (e.g., identifying a specific word as an "author" rather than
just text). This also makes data more available to "reading machines" for individuals with visual
impairments.

2
Unit 3:XML & JavaScript

 Data Integrity and Validation: XML schemas (XSD) or Document Type Definitions (DTD)
can be used to verify that the data extracted from or used to create a PDF is accurate and follows
a predefined structure.

 Standardized Industry Applications: Many modern standards, such as the CDISC Define-
XML, use XML to provide metadata that explains the content of clinical trial data submitted in
other formats like PDF.

 Dynamic Content Creation: Tools like Adobe Acrobat allow for the conversion of PDFs to
XML, making it easier to repurpose static document content for web applications or mobile
interfaces.

XML Usages
XML is used in many aspects of web development, often to simplify data storage and sharing.

 XML Separates Data from HTML: If you need to display dynamic data in your HTML
document, it will take a lot of work to edit the HTML each time the data changes. With
XML, data can be stored in separate XML files. This way you can concentrate on using
HTML for layout and display, and be sure that changes in the underlying data will not
require any changes to the HTML. With a few lines of JavaScript code, you can read an
external XML file and update the data content of your web page.
 XML Simplifies Data Sharing: In the real world, computer systems and databases
contain data in incompatible formats. XML data is stored in plain text format. This
provides a software- and hardware-independent way of storing data. This makes it much
easier to create data that can be shared by different applications.
 XML Simplifies Data Transport: One of the most time-consuming challenges for
developers is to exchange data between incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.
 XML Simplifies Platform Changes: Upgrading to new systems (hardware or software
platforms), is always time consuming. Large amounts of data must be converted and
incompatible data is often lost. XML data is stored in text format. This makes it easier to
expand or upgrade to new operating systems, new applications, or new browsers, without
losing data.
 XML Makes Your Data More Available: Different applications can access your data,
not only in HTML pages, but also from XML data sources. With XML, your data can be
available to all kinds of "reading machines" (Handheld computers, voice machines, news
feeds, etc), and make it more available for blind people, or people with other disabilities.
 XML Used to Create New Internet Languages: A lot of new Internet languages are
created with XML. Here are some examples:

3
Unit 3:XML & JavaScript

 XHTML

WSDL (Web Services Description Language) for describing available web services
WAP and WML (Wireless Markup Language) as markup languages for handheld devices
RSS (Really Simple Syndication / Rich Site Summary) languages for news feeds
RDF (Resource Description Framework), a family of W3C spec, and OWL (Web Ontology
Language) for describing resources and ontology
SMIL (Synchronized Multimedia Integration Language) for describing multimedia for the
web

Java Script

What is JavaScript?

JavaScript is a dynamic computer programming language. It is lightweight and most commonly


used as a part of web pages, whose implementations allow client-side script to interact with the
user and make dynamic pages. It is an interpreted programming language with object-oriented
capabilities.

JavaScript is a single-threaded programming language that we can use for client-side or server-
side development. It is a dynamically typed programming language, which means that we dont
care about variable data types while writing the JavaScript code. Also, it contains the control
statements, operators, and objects like Array, Math, Data, etc.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has
been embedded in Netscape and other web browsers.

History of JavaScript

JavaScript is developed by Brendan Eich, a computer scientist and programmer at Netscape


Communications Corporation. The initial name of the JavaScript was the 'Mocha'. After that, it
changed to 'LiveScript', and then 'JavaScript'.

Between 1996 and 1997, the European Computer Manufacturers Association (ECMA)
standardized JavaScript. After that, 3 revisions of the JavaScript have been done.

In ES5 (2009), [Link] was introduced to use JavaScript as a server-side language.


The ES6 (2015) was a significant revision of JavaScript, introducing advanced features into
JavaScript.

4
Unit 3:XML & JavaScript

Currently, JavaScript has reached the version ES14. ES14 (ECMAScript 2023) the 14th version,
was released in June 2023.

Client-Side JavaScript

Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need not be a static HTML but can include programs that interact with
the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail
address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are
valid they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.

The Popular client-side libraries for JavaScript development are ReactJS, NextJS, Vue JS,
Angular JS, etc.

Server-Side JavaScript

In the early days, JavaScript was used for front-end development to add behaviors to HTML
pages. Since 2009, JavaScript is also used as a server-side programming language to build
scalable and dynamic web applications.

[Link] is one of the best and most popular JavaScript runtime environments for building the
server of applications using JavaScript. Using [Link], we can execute the JavaScript code
outside the browser and manage the server task. The server tasks can be an interaction with the
database, APIS, file handling, or maybe network communication. Due to the event-driven
architecture of [Link], it is faster than other server-side programming languages.

Adding JavaScript in HTML Document


JavaScript can be included in an HTML document to add interactivity and dynamic behavior to
web pages. It allows the browser to execute scripts that can modify content, handle events, and
communicate with servers.
 Inline JavaScript: Code written directly inside HTML tags using attributes like onclick.
 Internal JavaScript: Script written inside the <script> tag within the HTML file.
 External JavaScript: JavaScript stored in a separate .js file and linked using the <script
src="[Link]"></script> tag.

5
Unit 3:XML & JavaScript

Inline JavaScript
You can write JavaScript code directly inside the HTML element using
the onclick, onmouseover, or other event handler attributes.

<html>

<head></head>

<body>

<h2>

Adding JavaScript in HTML Document

</h2>

<button onclick="alert('Button Clicked!')">

Click Here

</button>

</body>

</html>

Internal JavaScript (Within <script> Tag)


You can write JavaScript code inside the <script> tag within the HTML file. This is known as
internal JavaScript and is commonly placed inside the <head> or <body> section of the HTML
document.

1. JavaScript Code Inside <head> Tag


Placing JavaScript within the <head> section of an HTML document ensures that the script is
loaded and executed as the page loads. This is useful for scripts that need to be initialized before
the page content is rendered.

<html>

<head>

<script>

function myFun() {

6
Unit 3:XML & JavaScript

[Link]("demo")

.innerHTML = "Content changed!";

</script>

</head>

<body>

<h2>

Add JavaScript Code

inside Head Section

</h2>

<h3 id="demo" style="color:green;">

GeeksforGeeks

</h3>

<button type="button" onclick="myFun()">

Click Here

</button>

</body>

</html>

2. JavaScript Code Inside <body> Tag


JavaScript can also be placed inside the <body> section of an HTML page. Typically, scripts
placed at the end of the <body> load after the content, which can be useful if your script depends
on the DOM being fully loaded.
<html>

<head></head>

<body>

7
Prof. Ashwini R B (KLE BCA SANKESHWAR)
Unit 3:XML & JavaScript

<h2>

Add JavaScript Code

inside Body Section

</h2>

<h3 id="demo" style="color:green;">

GeeksforGeeks

</h3>

<button type="button" onclick="myFun()">

Click Here

</button>

<script>

function myFun() {

[Link]("demo")

.innerHTML = "Content changed!";

</script>

</body>

</html>

External JavaScript (Using External File)


For larger projects or when reusing scripts across multiple HTML files, you can place your
JavaScript code in an external .js file. This file is then linked to your HTML document using the
src attribute within a <script> tag.
<html>

<head>

<script src="[Link]"></script>

</head>

8
Unit 3:XML & JavaScript

<body>

<h2>

External JavaScript

</h2>

<h3 id="demo" style="color:green;">

GeeksforGeeks

</h3>

<button type="button" onclick="myFun()">

Click Here

</button>

</body>

</html>

Object Oriented & Java Script:

1. Object

An object is a real-world entity that has properties (data) and methods (functions).
In JavaScript, objects are the basic building blocks of Object Oriented Programming.

Example:
Student, Car, Book, Employee are examples of objects.

JavaScript Example:

let student = {
name: "Ravi",
age: 20,
display: function() {
[Link]([Link]);
}
};

Here:

9
Unit 3:XML & JavaScript

 name and age are properties


 display() is a method
 student is an object

2. Class

A class is a blueprint or template used to create objects.


It defines the structure and behavior of objects.

In JavaScript, classes were introduced in ES6 to support Object Oriented Programming.

JavaScript Example:

class Student {
constructor(name, age) {
[Link] = name;
[Link] = age;
}

display() {
[Link]([Link]);
}
}

let s1 = new Student("Ravi", 20);

Here:

 Student is a class
 s1 is an object

The Four Pillars of OOP

The four main principles (pillars) of Object Oriented Programming are:

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

1. Encapsulation

Encapsulation is the process of wrapping data and methods into a single unit (object) and
restricting direct access to data.

It protects data from unauthorized access.

10
Unit 3:XML & JavaScript

JavaScript Example:

class BankAccount {
constructor(balance) {
[Link] = balance;
}

deposit(amount) {
[Link] += amount;
}
}

Here:
Data (balance) and method (deposit) are combined in one class.

4. Inheritance

Inheritance is the process by which one class acquires properties and methods from another
class.

It helps in code reusability.

Parent class → Superclass


Child class → Subclass

JavaScript Example:

class Animal {
eat() {
[Link]("Eating");
}
}

class Dog extends Animal {


bark() {
[Link]("Barking");
}
}

Here:

 Animal is the parent class


 Dog is the child class
 Dog inherits the eat() method

11
Unit 3:XML & JavaScript

5. Polymorphism

Polymorphism means one method can perform different tasks depending on the object.

It allows the same function name to behave differently.

JavaScript Example:

class Shape {
draw() {
[Link]("Drawing shape");
}
}

class Circle extends Shape {


draw() {
[Link]("Drawing circle");
}
}

Here:
The draw() method works differently for different classes.

6. Abstraction

Abstraction means hiding internal implementation details and showing only essential features to
the user.

It reduces complexity and improves usability.

JavaScript Example:

function startCar() {
[Link]("Car started");
}

User only sees the result, not the internal process.

Example: Student Management System

We will use one class (Student) and show how it demonstrates:

 Object
 Class
 Encapsulation
 Inheritance

12
Unit 3:XML & JavaScript

 Polymorphism
 Abstraction

JavaScript Example

// Parent Class (Encapsulation + Abstraction)


class Student {
constructor(name, marks) {
[Link] = name; // Data
[Link] = marks;
}

// Method (Abstraction)
display() {
[Link]("Student Name: " + [Link]);
}

// Method for result


result() {
[Link]("Result declared");
}
}

// Child Class (Inheritance)


class BCAStudent extends Student {
constructor(name, marks, course) {
super(name, marks);
[Link] = course;
}

// Polymorphism (Method Overriding)


result() {
if ([Link] >= 40)
[Link]("Pass");
else
[Link]("Fail");
}
}

// Object Creation
let s1 = new BCAStudent("Ravi", 65, "BCA");

// Using methods
[Link]();
[Link]();

13
Unit 3:XML & JavaScript

Core Syntactic Characteristics


 Case Sensitivity: JavaScript is strictly case-sensitive. Identifiers such
as myVariable, MyVariable, and MYVARIABLE are treated as distinct entities.

 Optional Semicolons: While statements are typically terminated with a semicolon (;), they are
often optional because the engine can use Automatic Semicolon Insertion (ASI) to end
statements at line breaks.

 Dynamic Typing: Variables do not have a fixed data type. A single variable can be reassigned
to different types (e.g., from a number to a string) during execution.

 Identifier Rules: Names for variables and functions must start with a letter, underscore (_), or
dollar sign ($). Subsequent characters can also include digits (0–9).

 Whitespace & Indentation: Spaces, tabs, and newlines are generally ignored by the interpreter,
allowing developers to format code for better readability.

 Comments: Supports two standard formats for documentation and notes:

o Single-line: Uses //.

o Multi-line: Uses /* ... */.

 Lexical Scoping: Originally only function-scoped (using var), modern JavaScript (ES6+)
supports block-level scoping through the let and const keywords.

Language Values and Literals


JavaScript distinguishes between Literals (fixed values) and Variables (changeable values).
 Numeric Literals: Written as decimals (e.g., 10.5), integers (100), or using special formats like
hexadecimal (0x), octal (0o), and binary (0b).

 String Literals: Textual data enclosed in single (') or double (") quotes, or backticks (`) for
template literals that allow embedded expressions.

 Boolean Literals: Represented by the keywords true and false.

Key Components
 Keywords: Reserved words like if, for, function, and return that have predefined meanings and
cannot be used as identifiers.

 Operators: Includes arithmetic (+, -, *, /), assignment (=, +=), and comparison (==, ===)
operators to perform computations.
14
Unit 3:XML & JavaScript

 Expressions: Combinations of variables, literals, and operators that evaluate to a single value.

 Control Structures: Uses constructs like if-else blocks, switch statements,


and while or for loops to manage program flow

Data Types
Variables hold values, and every value has a specific data type that defines the kind of
information it holds. These data types are broadly categorized into two groups: Primitive Data
Types and Non-Primitive Data Types. Let us discuss it one by one.
1. Primitive Data Types
Primitive data types are the built-in data types provided by JavaScript. They represent
single values and are not mutable. JavaScript supports the following primitive data types:

1.1 Number:
Number data type in JavaScript can be used to hold decimal values as well as values
without decimals.
Example: Below is an example.
let x = 250;

let y = 40.5;

[Link]("Value of x=" + x);

[Link]("Value of y=" + y);

Output

Value of x=250
Value of y=40.5

1.2 String:
The string data type in JavaScript represents a sequence of characters that are surrounded by
single or double quotes.
Example: Below is an example.
let str = 'Hello All';

let str1 = "Welcome to my new house";

[Link]("Value of str=" + str);

[Link]("Value of str1=" + str1);

Output
Value of str=Hello All
Value of str1=Welcome to my new house

15
Unit 3:XML & JavaScript

1.3 Undefined:
This means that a variable has been declared but has not been assigned a value, or it has been
explicitly set to the value `undefined`.
Example: Below is an example.
let x;

[Link](x); // Outputs: undefined

OUTPUT

1.4 Boolean:
The boolean data type can accept only two values i.e. true and false.
Example: Below is an example.
let x;

[Link](x); // Outputs: undefined

Output:

1.5 Null:
This data type can hold only one possible value that is null.
Example: Below is an example.
let x = null;

[Link] ("Value of x=" + x);

Output
Value of x=null

16
Unit 3:XML & JavaScript

1.6 BigInt:
BigInt data type can represent numbers greater than 253-1 which helps to perform operations on
large numbers. The number is specified by writing 'n' at the end of the value
Example: Below is an example.
let bigNum = 123422222222222222222222222222222222222n
[Link](bigNum)
Output
123422222222222222222222222222222222222n

1.7 Symbol:
Symbol data type is used to create objects which will always be unique. these objects can be
created using Symbol constructor.
Example: Below is an example.
let sym = Symbol("Hello")

[Link](typeof(sym));

[Link](sym);

Output
symbol
Symbol(Hel
2. Non-primitive Data Types

Non-primitive data types, also known as reference types, are objects and derived data types.
They can store collections of values or more complex entities. The two key non-primitive data
types in JavaScript are:

Below is a list of Non-primitive data types.

2.1 Object:

An object in Javascript is an entity having properties and methods. Everything is an object in


javascript.

How to create an object in javascript:

 Using Constructor Function to define an object:

// Create an empty generic object


let obj = new Object();

// Create a user defined object


let mycar = new Car();

17
Unit 3:XML & JavaScript

Example: Below is an example

// Creating object with the name person

let person = {

firstName: "Luiza",

lastName: "Shaikh",

};

// Print the value of object on console

[Link]([Link]

+ " " + [Link]);

Output

Luiza Shaikh

2.2 Array:

With the help of an array, we can store more than one element under a single name.

Ways to declare a single-dimensional array:

// Call it with no arguments


let a = new Array();

// Call it with single numeric argument


let b = new Array(10);

// Explicitly specify two or


// more array elements
let d = new Array(1, 2, 3, "Hello");

Example: Below is an example.

let a = new Array();

let b = new Array(10);

let d = new Array(1, 2, 3, "Hello");

18
Unit 3:XML & JavaScript

[Link]("value of a=" + a);

[Link]("value of b" + b);

[Link]("value of d=" + d);

Output

value of a=

value of b,,,,,,,,,

value of d=1,2,3,Hello

JavaScript Operators
Developers often have to write code that does mathematical and logical calculations. JavaScript
provides a very comprehensive list of operators which can be used to perform such tasks.
Operators in JavaScript are broadly divided as:

 Arithmetic Operators

 Increment/Decrement Operators

 Assignment Operators

 Comparison Operators

 Other Operators

JavaScript Arithmetic Operators

An arithmetic operator in JavaScript is used to perform arithmetic on numbers (the numbers can
be variables, literals, or expressions). Arithmetic operations typically operate on two numbers.

19
Unit 3:XML & JavaScript

Increment & Decrement Operators in JavaScript

Increment (two plus sign) ++ & Decrement (two minus sign) -- Operators are used to increase or
decrease the value of a variable by 1. Depending on whether the operator sign is used before or
after the variable, it produces a different result. However, it still increments or decrements by 1.

let count = 0;

[Link](count); // prints 0

count++; // first assign the current value back to count and then increase it by 1

++count; // first increase the value by 1 and then assign the new value to count

JavaScript Assignment Operators

Assignment operator or equal sign = is used for assigning the value on the right-hand side of the
equal sign to the variable on the left-hand side of the equal sign. It is the most commonly used
operator in JavaScript as there is always a need for assigning the value to a variable.

Increment and Decrement Operators also have a shorthand notation that uses the assignment
operator. While increment operator ++ and decrement operator -- is used to increase or decrease
the value by 1, sometimes there is a need to increase or decrease the value by a different amount.
In this case a variation of increment += and decrement -= is used.

20
Unit 3:XML & JavaScript

While writing code in JavaScript, there is always a need to make logical decisions in code.
Comparison operators are often used while writing logical statements. They compare two values
and return a boolean value either true or false. All the values are either truthy or falsy in
JavaScript and hence using comparison operators always returns a true or false value.

JavaScript Comparison Operators

One key thing to note here is that JavaScript allows both non-strict == and strict === comparison
of two values. It is highly recommended that Developers in JavaScript always use triple equal
sign === or strict equality comparison. == sign compares only the values to be either truthy or
falsy while === compares both the values and as well the type of both the values to be equal for
a more strict comparison.

21
Unit 3:XML & JavaScript

Other JavaScript Operators

Here are some of the other operators available in JavaScript:

JavaScript Bitwise Operators

Bitwise operators are used to perform operations on binary representations of numbers. Bitwise
operators convert any numeric operand in the operation into a 32-bit number, before returning a
standard JavaScript number.

JavaScript Logical Operators

Logical operators in JavaScript allow a program to make a decision based on multiple


conditions, where each operand can evaluate to a true or false value.

JavaScript Ternary Operators

22
Unit 3:XML & JavaScript

The ternary or conditional operator in JavaScript can be used to simplify an if…else statement. A
ternary operator performs an evaluation on a condition then executes a block of code based on
that condition, and as a result, takes three operands.

const whatToWear = isWeekend ? “jeans”: “suit”;

JavaScript Typeof Operators

The typeof operator in JavaScript returns a string indicating the type of the unevaluated operand.

Expressions
An expression is a block of code that evaluates to a value. A statement is any block of code that
is performing some action.

The distinction between an expression and a statement is important because an expression is a


subset of a statement. You can use an expression wherever a statement is expected, but this does
not work vice versa.

Conceptually speaking, there are two kinds of expressions: those that perform some sort of
assignment and those that evaluate to a value.

For example, x = 10 is an expression that performs an assignment. This expression itself


evaluates to 10. Such expressions make use of the assignment operator.

On the flip side, the expression 10 + 9 simply evaluates to 19. These expressions make use of
simple operators.

There are five primary categories of expression in JavaScript:

 Arithmetic: uses arithmetic operators (+ - * / %).

 String: uses string operators and evaluates to a character string.

 Logical: evaluates to a boolean value of either True or False and uses boolean operators.

 Primary expressions: Consists of basic keywords and expressions.

 Left-hand side expressions: Left-hand side values which are the destination for the
assignment operator.

Screen Output:

JavaScript uses methods like [Link](), alert(), [Link](), and DOM updates to show
output, whether for debugging, giving alerts, or changing web content.

23
Unit 3:XML & JavaScript

1. innerHTML Property

The innerHTML property is used with the HTML element. JavaScript can be used to select an
element using the [Link](id) method, and then use the innerHTML property
to display the output on the specified element (selected element).

Syntax:

[Link]("id").innerHTML;

Example: The [Link](id) method with innerHTML property is used to


display the output.

<!DOCTYPE html>

<html lang="en">

<head> </head>

<body>

<p id="GFG"></p>

<!-- Script to use innerHTML -->

<script>

[Link]("GFG").innerHTML

= "Hello Geeks!";

</script>

</body>

</html>

2. [Link]()

The [Link]() method is used for logging messages to the console. It is a debugging tool
available in most web browsers. It is used during development to output information about the
state of the program.

Syntax:

[Link]();

Example: This example uses the [Link]() property to display data.

24
Unit 3:XML & JavaScript

<!DOCTYPE html>

<html lang="en">

<head> </head>

<body>

<!-- Script to use [Link]() -->

<script>

[Link]("Hello Geeks!");

</script>

</body>

</html>

3. [Link]()

To use the [Link](), simply call this method and provide the content you want to be
written to the document. This method is often used for directly adding content to the HTML
document while it is being parsed.

Syntax:

[Link]();

Example: The [Link]() method display the output.

<!DOCTYPE html>

<html lang="en">

<head> </head>

<body>

<!-- Script to uses [Link]() -->

<script>

[Link]("Hello Geeks!");

</script>

</body></html>

25
Unit 3:XML & JavaScript

4. [Link]()

The [Link]() method is used to display an alert box with a specified output (or message)
and an OK button.

Syntax:

[Link]();

Example: The [Link]() method display the output data.

<!DOCTYPE html>

<html lang="en">

<head> </head>

<body>

<!-- Script to use [Link]() -->

<script>

[Link]("Hello Geeks!");

</script>

</body>

</html>

5. [Link]()

The [Link]() method is used to open the browser's print dialog, allowing the user to print
the current page. JavaScript does not contain any default print object or methods.

Syntax:

[Link]();

Example: The [Link]() method prints the current page.

<!DOCTYPE html>

<html>

<body>

26
Unit 3:XML & JavaScript

<button onclick="[Link]()">

Click here to Print

</button>

</body>

</html>

Keyboard Input
Taking keyboard input in JavaScript is essential for building interactive web applications.
Whether you're creating a game, handling user login, or simply getting user preferences,
JavaScript provides several ways to collect data from the keyboard.

Using prompt() for User Input

The prompt() function is one of the simplest ways to get user input in JavaScript. This built-in
function opens a dialog box where the user can type something, and the value is returned as a
string.

Syntax

let userInput = prompt("Enter some text:");

let userName = prompt("What is your name?");

if (userName) {

alert("Hello, " + userName + "!");

} else {

alert("No name entered.");

Using Event Listeners for Keyboard Input

For more advanced scenarios, such as detecting real-time typing or handling specific keys, you
can use JavaScript's event handling system. By listening for keyboard events (keydown,
keypress, keyup), you can capture input as the user interacts with the keyboard.

27
Unit 3:XML & JavaScript

1. keydown Event

The keydown event occurs when a key is pressed down, and it captures all key types, including
special keys like Esc, Enter, and arrow keys.

[Link]('keydown', function(event) {

[Link]('Key pressed: ' + [Link]);

});

[Link] Event

The keypress event is triggered when a character key is pressed, i.e., when a printable character
like letters, numbers, or symbols is entered. It does not fire for non-printable keys like Shift, Ctrl,
or Arrow.

[Link]('keypress', function(event) {

[Link]('Key pressed: ' + [Link]);

});

[Link] Event

The keyup event occurs when the key is released, and it is often used when you want to detect
input after the user finishes typing or pressing a key.

[Link]('keyup', function(event) {

[Link]('Key released: ' + [Link]);

});

Control Statements
JavaScript control statement is used to control the execution of a program based on a specific
condition. If the condition meets then a particular block of action will be executed otherwise it
will execute another block of action that satisfies that particular condition.

Types of Control Statements in JavaScript

 Conditional Statement: These statements are used for decision-making, a decision

 n is made by the conditional statement based on an expression that is passed. Either YES
or NO.

28
Unit 3:XML & JavaScript

 Iterative Statement: This is a statement that iterates repeatedly until a condition is met.
Simply said, if we have an expression, the statement will keep repeating itself until and
unless it is satisfied.

1: If Statement

In this approach, we are using an if statement to check a specific condition, the code block gets
executed when the given condition is satisfied.

Syntax

if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}

Now let's understand this with the help of example:

const num = 5;

if (num > 0) {

[Link]("The number is positive.");

};

2: Using If-Else Statement

The if-else statement will perform some action for a specific condition. If the condition meets
then a particular code of action will be executed otherwise it will execute another code of action
that satisfies that particular condition.

Syntax

if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}

Now let's understand this with the help of example:

let num = -10;

29
Unit 3:XML & JavaScript

if (num > 0)

[Link]("The number is positive.");

else

[Link]("The number is negative");

Output

The number is negative

3: Using Switch Statement

The switch case statement in JavaScript is also used for decision-making purposes. In some
cases, using the switch case statement is seen to be more convenient than if-else statements.

Syntax

switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Now let's understand this with the help of example:

let num = 5;

switch (num) {

case 0:

[Link]("Number is zero.");

30
Unit 3:XML & JavaScript

break;

case 1:

[Link]("Nuber is one.");

break;

case 2:

[Link]("Number is two.");

break;

default:

[Link]("Number is greater than 2.");

};
Output

Number is greater than 2.

4: Using the Ternary Operator (Conditional Operator)

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing
conditional statements in JavaScript.

Syntax

condition ? value if true : value if false

Now let's understand this with the help of example

let num = 10

let result = num >= 0 ? "Positive" : "Negative";

[Link](`The number is ${result}.`);


Output

The number is Positive.

5: Using For loop

In this approach, we are using for loop in which the execution of a set of instructions repeatedly
until some condition evaluates and becomes false

31
Unit 3:XML & JavaScript

Syntax

for (statement 1; statement 2; statement 3) {


// Code here . . .
}

Now let's understand this with the help of example:

for (let i = 0; i <= 10; i++) {

if (i % 2 === 0) {

[Link](i);

};
Output

0
2
4
6
8
10

6: Using While loop

The while loop repeats a block of code as long as a specified condition is true.

Syntax

while (condition) {
// code block
}

Now let's understand this with the help if example

let i = 1;

while (i <= 5) {

[Link](i);

i++;

32
Unit 3:XML & JavaScript

Output

1
2
3
4
5

7: Using Do-While loop

The do-while loop is similar to the while loop, except that the condition is evaluated after the
execution of the loop's body. This means the code block will execute at least once, even if the
condition is false.

Syntax

do {
// code block
} while (condition);

Now let's understand this with the help of example:

let i = 1;

do {

[Link](i);

i++;

} while (i <= 5);

Output

1
2
3
4
5

Object Creation & Modification

JavaScript objects are fundamental to working with the language, allowing developers to
organize and manipulate data efficiently. In this post, we’ll dive deep into creating,
manipulating, and working with JavaScript objects, covering key methods and their real-
world applications.

33
Unit 3:XML & JavaScript

What are JavaScript Objects?

Objects in JavaScript are collections of key-value pairs, where keys are strings (or Symbols)
and values can be any data type, including other objects or functions.

Why Use Objects?

 Organize related data together.

 Improve code readability and maintainability.

 Enable efficient data manipulation.

How to Create an Object?

We can create objects using three primary methods:

[Link] Literal Syntax (Most Common)

const person = {
name: "Lokesh",
age: 25,
job: "Web Developer"
};
[Link]([Link]); // Lokesh

2. Using the new Object() Constructor

const car = new Object();


[Link] = "BMW";
[Link] = "Model 3";
[Link]([Link]); // BMW

[Link] a Constructor Function

function Person(name, age) {


[Link] = name;
[Link] = age;
}
const user = new Person("Lokesh", 25);
[Link]([Link]); // Lokesh

34
Unit 3:XML & JavaScript

Manipulating Objects

Once created, we can update, delete, and modify objects dynamically.

1. Adding or Updating Properties

const student = { name: "Lokesh" };


[Link] = 25; // Add new property
[Link] = "Mukesh"; // Update existing property
[Link](student); // { name: "Mukesh", age: 25 }

2. Deleting Properties

delete [Link];
[Link](student); // { name: "Lokesh" }

35

You might also like