0% found this document useful (0 votes)
17 views130 pages

Understanding Client-Side vs Server-Side JavaScript

iwt unit 3

Uploaded by

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

Understanding Client-Side vs Server-Side JavaScript

iwt unit 3

Uploaded by

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

Introduction

JavaScript is a high-level, dynamic, and interpreted programming language used to


create interactive and dynamic features on web pages and web applications. It enables
developers to implement complex functionalities such as dynamic content updates,
animation, multimedia handling, and user interactions directly in the browser. As a
core technology of the web alongside HTML and CSS, JavaScript is used both on the
client-side in browsers and, with environments like [Link], on the server-side as well

What does client side mean?


In web development, 'client side' refers to everything in a web application that is
displayed or takes place on the client (end user device). This includes what the user
sees, such as text, images, and the rest of the UI, along with any actions that an
application performs within the user's browser.
Markup languages like HTML and CSS are interpreted by the browser on the client
side. In addition, many contemporary developers are including client-side processes in
their application architecture and moving away from doing everything on the server
side; business logic for dynamic webpages*, for instance, usually runs client side in a
modern web application. Client-side processes are almost always written in JavaScript.
In the [Link] example above, the HTML, CSS, and JavaScript that dictate how the
Netflix main page appears to the user are interpreted by the browser on the client side.
The page can also respond to 'events': For instance, if the user's mouse hovers over one
of the movie thumbnail images, the image expands and adjacent thumbnails move
slightly to one side to make room for the larger image. This is an example of a client-
side process; the code within the webpage itself responds to the user's mouse and
initiates this action without communicating with the server.
The client side is also known as the frontend, although these two terms do not mean
precisely the same thing. Client-side refers solely to the location where processes run,
while frontend refers to the kinds of processes that run client-side.
*A dynamic webpage is a webpage that does not display the same content for all users
and changes based on user input. The Facebook homepage is a dynamic page; the
Facebook login page is for the most part static.
What does server side mean?
Much like with client side, 'server side' means everything that happens on the server,
instead of on the client. In the past, nearly all business logic ran on the server side, and
this included rendering dynamic webpages, interacting with databases, identity
authentication, and push notifications.
The problem with hosting all of these processes on the server side is that each request
involving one of them has to travel all the way from the client to the server, every time.
This introduces a great deal of latency. For this reason, contemporary applications run
more code on the client side; one use case is rendering dynamic webpages in real time
by running scripts within the browser that make changes to the content a user sees.
Like with 'frontend' and 'client-side,' backend is also a term for the processes that take
place on the server, although backend only refers to the types of processes and server-
side refers to the location where processes run.
What is client-side scripting? What is server-side scripting?
Client-side scripting simply means running scripts, such as JavaScript, on the client
device, usually within a browser. All kinds of scripts can run on the client side if they
are written in JavaScript, because JavaScript is universally supported. Other scripting
languages can only be used if the user's browser supports them.
Server-side scripts run on the server instead of the client, often in order to deliver
dynamic content to webpages in response to user actions. Server-side scripts don't have
to be written in JavaScript, since the server may support a variety of languages. Scripts
run client-side and server-side:
JavaScript Frameworks JavaScript Libraries
Angular React
[Link] jQuery
[Link] Lodash
[Link] [Link]
[Link] [Link]
Svelte [Link]
[Link] [Link]
Meteor [Link]
Example of Client-
Side JavaScript Script
xml
<!DOCTYPE html>
<html>
<head>
<title>Client-Side Script Example</title>
<script>
// This JavaScript runs on the client side in the browser
// Function to display a list of cities dynamically
function displayCities() {
var cities = ["New York", "Dhanbad", "Paris", "London", "Mumbai"];
var ulElement = [Link]("cityList");
for(var i = 0; i < [Link]; i++) {
var listItem = [Link]("li");
[Link] = cities[i]; [Link](listItem); }}
</script>
</head>
<body onload="displayCities()">
<h1>List of Cities</h1>
<ul id="cityList"></ul>
</body>
</html>

Explanation
The <script> tag contains JavaScript code executed when the page loads.
The function display Cities dynamically creates <li> elements and inserts city names
into the unordered list <ul>.
This script runs entirely in the browser (client-side), updating page content without
server involvement.
This usage is typical for client-side scripts, providing fast, interactive user experiences
by manipulating the HTML DOM directly in the browser.
Has function scope (or global scope if declared outside a function).
Variable
In JavaScript, a variable is a named container used to store data values. These values
can be of various data types, such as numbers, strings, objects, or arrays. Variables are
fundamental for storing, retrieving, and manipulating data within a program.
There are three main keywords used to declare variables in JavaScript: var, let,
and const.
var
o The oldest way to declare variables in JavaScript.
o Has function scope or global scope, meaning if declared inside a function,
it's accessible throughout that function; otherwise, it's globally accessible.
o Allows for re-declaration and re-assignment within its scope.
var x = 10;
[Link](x); // Output: 10
var x = 20; // Re-declaration is allowed
[Link](x); // Output: 20
x = 30; // Re-assignment is allowed
[Link](x); // Output: 30
let:
o Introduced in ES6 (ECMAScript 2015).
o Has block scope, meaning it's only accessible within the block
(e.g., if statement, for loop, or curly braces {}) where it's declared.
o Allows for re-assignment but not re-declaration within the same scope.
JavaScript
let y = 100;
[Link](y); // Output: 100
y = 200; // Re-assignment is allowed
[Link](y); // Output: 200
// let y = 300; // This would throw an error: Identifier 'y' has already been declared
const:
o Also introduced in ES6.
o Has block scope, similar to let.
o Declares a constant, meaning its value cannot be re-assigned after initialization. It must
be initialized at the time of declaration.
JavaScript
const PI = 3.14;
[Link](PI); // Output: 3.14
// PI = 3.14159; // This would throw an error: Assignment to constant variable.

Naming Conventions:
Variable names must start with a letter, an underscore (_), or a dollar sign ($). They
can contain letters, numbers, underscores, and dollar signs. JavaScript is case-sensitive,
so myVar and myvar are considered different variables. It is common practice to use
variable names (e.g., firstName, totalAmount).
Defining Functions
In JavaScript, a function is a block of code defined once but can be executed, or
"invoked," many times. Functions can have parameters, which are like variables that
are local to the function. The instructions inside the function are known as the function
body and are enclosed in curly braces {} .
Example 1
function sayname(){
[Link](“h”);
[Link](“e”);
[Link](“l”);
[Link](“l”);
[Link](“o”);
}
sayname()

example 2:
function sayname(n1,n2)//parameters {
[Link](n1+n2);
}
sayname(3+4);
// sayname(3+”a”)//arguments
Example 3:
function sayname(n1,n2) {
[Link](n1+n2);
}
sayname(3+4);
//that not print
sayname(3+”a”)
const result= sayname(3+4)// output 7
[Link](“result”,result)

example 4
function sayname(n1,n2) {
let result=n1+n2
return result
[Link](“hello js”);// they didn’t print (after return they didn’t store any .)
}
sayname(3+4)

1. Function Declarations
This is the most common and traditional way to define a function. You use
the function keyword, followed by the function's name and its code block.
Example:
javascript
// Function is declared with a specific name. example 2:
function sayname(n1,n2)//parameters {
[Link](n1+n2);
}
sayname(3+4);
// sayname(3+”a”)//arguments
2. Function Expressions
A function expression is created and assigned to a variable, treating the function as a
value. The function can be anonymous (without a name) or named.
Example (Anonymous Function Expression):
// A function to find the square of a number, assigned to the `square` variable
const square = function(num) {
return num * num;
};

// Call the function using the variable name


[Link](square(5)); // Output: 25
3. Arrow Functions
Introduced in ES6, arrow functions provide a more concise syntax for function
expressions. They are always anonymous by default.
Example:
javascript
// A concise arrow function for a single expression.
const multiply = (a, b) => a * b;

[Link](multiply(5, 4)); // Output: 20

// An arrow function with multiple lines requires curly braces and a return statement.
const getGreeting = (name) => {
const greeting = `Hello, ${name}!`;
return greeting;
};
1 The Purpose of Loops
In JavaScript, a loop is a fundamental control structure used to execute a block of code
repeatedly. Instead of writing the same code over and over, loops provide a way to
automate repetitive tasks, making programs more efficient and easier to read. The
examples below are designed to be run in a JavaScript console (like in your browser's
developer tools) or in a [Link] environment.
The for Loop
The for loop is ideal when you know the number of times you want to iterate. It
combines the initialization of a counter, the condition for continuing the loop, and the
increment or decrement into a single line.
Example: Print numbers 0 through 4
javascript
for (let i = 0; i < 5; i++) {
[Link]("For loop iteration: " + i);
}
/*
Output:
For loop iteration: 0
For loop iteration: 1
For loop iteration: 2
For loop iteration: 3
For loop iteration: 4
*/
Use code with caution.
<!DOCTYPE html>
<html>
<head>
<title>For Loop Example</title>
</head>
<body>
<h1>For Loop Demonstration</h1>
<ul id="number-list"></ul>
<script>
const numberList = [Link]("number-list");
// The for loop iterates from i = 0 up to 4.
for (let i = 0; i < 5; i++) {
// On each iteration, it adds a new list item with the current number.
[Link] += `<li>Number: ${i}</li>`;
}
</script>
</body>
</html>

The while Loop


A while loop continues to execute a block of code as long as a specified condition is
true. It is useful when the number of iterations is not known in advance. The condition
is checked at the beginning of each iteration.
Example: Countdown from 5
javascript
let count = 5;
while (count > 0) {
[Link]("While loop countdown: " + count);
count--; // This is essential to prevent an infinite loop!
}

/*
Output:
While loop countdown: 5
While loop countdown: 4
While loop countdown: 3
While loop countdown: 2
While loop countdown: 1
*/
Use code with caution.

<!DOCTYPE html>
<html>
<head>
<title>While Loop Example</title>
</head>
<body>
<h1>While Loop Demonstration</h1>
<p id="countdown"></p>
<script>
let count = 5;
const countdownDisplay = [Link]("countdown");
let output = "";
// The while loop runs as long as the 'count' variable is greater than 0.
while (count > 0) {
output += `Countdown: ${count}... `;
count--; // This decreases the count, eventually stopping the loop.
}
output += "Blast off!";
[Link] = output;
</script>
</body>
</html>
The do...while Loop
The do...while loop is similar to the while loop, but it guarantees that the code block
will execute at least once, even if the condition is initially false. This is because the
condition is checked at the end of the loop.
Example: A loop that runs at least once
javascript
let i = 10;
do {
[Link]("Do-while loop iteration: " + i);
i++;
} while (i < 10); // The condition is false, but the code still runs once.

/*
Output:
Do-while loop iteration: 10
*/
Use code with caution.
<!DOCTYPE html>
<html>
<head>
<title>Do...While Loop Example</title>
</head>
<body>
<h1>Do...While Loop Demonstration</h1>
<p id="result"></p>
<script>
let i = 10;
let resultElement = [Link]("result");
let message = "";
// The code block runs once before the condition is checked.
do {
message = "This runs at least once.";
i++;
} while (i < 10); // Condition is false, so the loop stops after the first run.
[Link] = message;
</script>
</body>
</html>

The for...of Loop


This loop is used to iterate over the values of iterable objects, such as arrays and
strings. It provides a cleaner and more direct syntax for iterating over elements without
managing a counter variable.
Example: Iterate over an array
javascript
const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
[Link]("For-of loop: " + fruit);
}
/*
Output:
For-of loop: Apple
For-of loop: Banana
For-of loop: Cherry
*/

<!DOCTYPE html>
<html>
<head>
<title>For...of Loop Example</title>
</head>
<body>
<h1>For...of Demonstration (Fruit List)</h1>
<ul id="fruit-list"></ul>

<script>
const fruits = ["Apple", "Banana", "Cherry"];
const fruitList = [Link]("fruit-list");

// The for...of loop iterates directly over the values in the 'fruits' array.
for (const fruit of fruits) {
[Link] += `<li>${fruit}</li>`;
}
</script>

</body>
</html>

Use code with caution.


The for...in Loop
The for...in loop is used to iterate over the enumerable properties (or keys) of an
object. While it can be used with arrays, the for...of loop is the standard and
recommended way for iterating over array elements.
Example: Iterate over object properties
javascript
const person = {
name: "Alice",
age: 30,
city: "Wonderland"
};

for (const key in person) {


[Link](`For-in loop: ${key}: ${person[key]}`);
}

/*
Output:
For-in loop: name: Alice
For-in l
<!DOCTYPE html>
<html>
<head>
<title>For...in Loop Example</title>
</head>
<body>
<h1>For...in Demonstration</h1>
<ul id="person-details"></ul>
<script>
const person = {
name: "Alice",
age: 30,
city: "Wonderland"
};
const personDetails = [Link]("person-details");
// The for...in loop iterates over the keys of the 'person' object.
for (const key in person) {
[Link] += `<li>${key}: ${person[key]}</li>`;
}
</script>
</body>
</html>

1. Calling a Function with a Button Click


<!DOCTYPE html>
<html>
<body>
<button onclick="showMessage()">Show Welcome
Message</button>
<script>
function showMessage() {
alert("Welcome to JavaScript!");
}
</script>
</body>
</html>

Clicking the button runs the showMessage() function, displaying an


alert.

2. Passing Arguments to a Function


<!DOCTYPE html>
<html>
<body>
<button onclick="greet('Amit')">Greet Amit</button>
<button onclick="greet('Ravi')">Greet Ravi</button>
<script>
function greet(name) {
alert("Hello " + name + "!");
}
</script>
</body>
</html>

Here, the function is called with different names as arguments,


showing a personalized greeting.[4]

3. Changing the Content of a Web Page


<!DOCTYPE html>
<html>
<body>
<p id="demo">Original Text</p>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
[Link]("demo").innerHTML = "The text was
changed!";
}
</script>
</body>
</html>
This updates the content of the page when the button is clicked.

4. Using Event Listeners for Clean Code


<!DOCTYPE html>
<html>
<body>
<button id="eventBtn">Event Listener Example</button>
<script>
function showAlert() {
alert("Button clicked using event listener!");
}
[Link]("eventBtn").addEventListener("click",
showAlert);
</script>
</body>
</html>

This is a best practice for separating JavaScript logic from HTML


structure.
5. Change Style with a Function
<!DOCTYPE html>
<html>
<body>
<p id="styleText">Make me red!</p>
<button onclick="makeRed()">Red Text</button>
<script>
function makeRed() {
[Link]("styleText").[Link] = "red";
}
</script>
</body>
</html>

JavaScript provides three main types of pop-up boxes to interact with


users: alert, confirm, and prompt. They are simple dialog boxes
that appear on the web page and serve different purposes.
1. Alert Box
 Purpose: To display information or warning messages to the user.
 Behavior: Shows a message with an OK button; the user must
click OK to continue.
 Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="alert('This is an alert box!')">Show
Alert</button>
</body>
</html>

When clicked, this button shows a popup message with an OK


button.[1][2]

2. Confirm Box
 Purpose: To ask the user to confirm or cancel an action.
 Behavior: Shows a message with OK and Cancel buttons; returns
true if OK is clicked, false if Cancel.
 Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="showConfirm()">Show Confirm</button>
<script>
function showConfirm() {
var result = confirm('Are you sure you want to proceed?');
if(result) {
alert('You pressed OK!');
} else {
alert('You pressed Cancel!');
}
}
</script>
</body>
</html>
This example uses confirm to get user consent before proceeding
and alerts the result.

3. Prompt Box
 Purpose: To prompt the user to input some text.
 Behavior: Displays a message, input box, and OK/Cancel buttons;
returns the input string or null if canceled.
 Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="getName()">Enter Name</button>
<script>
function getName() {
var userName = prompt('Please enter your name:', 'Guest');
if(userName) {
alert('Hello, ' + userName + '!');
} else {
alert('You did not enter a name.');
}
}
</script>
</body>
</html>

This requests input and responds with a greeting or cancellation


message.

Summary Points
 These pop-up boxes halt page interaction until closed.
 Alert is for messages only; Confirm is for yes/no decisions; Prompt
collects input.
 They are easy to use and supported by all modern browsers.
 Use them sparingly as they interrupt user flow.
JavaScript objects are versatile and powerful structures designed to store collections
of data and behaviors (methods) as key-value pairs, facilitating data modeling,
organization, and abstraction in web development. They form the foundation for most
complex data structures and systems in JavaScript.[1][2][3]
Object Fundamentals
 Definition: An object is an unordered collection of properties, where each property
is a name/value pair. Values can be any type: strings, numbers, arrays, other objects,
or functions (methods).[4][2][1]
 Syntax: The most common way to create objects is with object literal syntax.
const person = {
firstName: "Steve",
lastName: "Jobs",
age: 56,
greet: function() {
return "Hello, " + [Link];
}
};

Objects in JavaScript
In JavaScript, an object is a collection of related data stored as key-value pairs, where
each key (also called a property name) has an associated value. Objects are used to
group and manage information and behaviour together, and they allow you to
organize complex data structures by encapsulating properties and methods (functions
stored as properties)
const person = {
firstName: "Steve",----------properties
lastName: "Jobs",
age: 56,
greet: function() {
return "Hello, " + [Link];----- methods
}
};

In JavaScript, there are four types of objects. They are as follows:


 User-defined objects

 Built-in objects ( such as Date and Math objects)

 Browser objects (such as window, navigator, and history objects)

 Document objects (for example, link, forms and images)

User-defined Objects in JavaScript


User-defined objects in JavaScript are custom objects created by
the programmer for specific programming tasks. They are
associated with properties and methods.
 For example, a person is an object.

There are three ways to create user-defined objects:


 By object literal

 By creating an instance of Object directly (using new keyword)

 Using object constructor

Object literal is the simplest and the most popular way to create a user-defined object
in JavaScript. We can create a user-defined object with several properties by using
object literal, as follows:
var person = {
// Declaration of properties of an object person.
firstName: "John",
lastName: "Herry",
age: 25,
skinColor: "White"
};
[Link] Object Literal:
This is the most common and concise way to create an object. You define the
object with key-value pairs inside curly braces {}.
javascript
let course = {
name: "JavaScript",
language: "Scripting",
level: "Beginner"
};
[Link]([Link]); // Output: JavaScript
[Link] Creating an Instance of Object Directly (Using new Keyword):
You can create an object using the new Object() syntax and then add properties.
javascript
let course = new Object();
[Link] = "JavaScript";
[Link] = "Scripting";
[Link]([Link]); // Output: Scripting
[Link] Object Constructor:
You define a constructor function and instantiate an object using
the new keyword with that constructor.
javascript
function Course(name, language) {
[Link] = name;
[Link] = language;
}
let myCourse = new Course("JavaScript", "Scripting");
[Link]([Link]); // Output: JavaScript

Built-in Objects in JavaScript


Built-in objects are native objects that are part of core JavaScript and they are defined
in ECMAScript standard. JavaScript supports the number of built-in objects.
These built-in objects are available for both client side JavaScript and server-side
applications. Some important built-in objects include:
 String object

 Array object

 Date object

 Math object

Here is an explanation of some of the most important built-in objects in JavaScript:

String Object
The String object represents a sequence of characters and provides methods to
manipulate strings. You can create string objects and use methods like charAt(),
substring(), toUpperCase(), split(), etc.

Example:
javascript
let message = "Hello, World!";
[Link]([Link]()); // Output: HELLO, WORLD!
Array Object
The Array object represents an ordered list of values. It provides methods such as
push(), pop(), shift(), unshift(), concat(), slice(), which allow adding, removing,
combining, and slicing arrays.

Example:

javascript
let numbers = [1, 2, 3];
[Link](4); // Adds 4 to the end
[Link](numbers); // Output: [1, 2, 3, 4]
Date Object
The Date object handles dates and times. It allows creation of date/time objects, and
methods to get or set specific components like year, month, day, hours, minutes, etc.

Example:

javascript
let currentDate = new Date();
[Link]([Link]()); // Current year
Math Object
The Math object contains properties and methods for mathematical operations such
as [Link](), [Link](), [Link](), [Link](), and more.

Example:

javascript
let randomNum = [Link](); // Generates a random number between 0 and 1
Browser Objects in JavaScript
Browser objects are those objects that interact with the browser window. These
objects are not part of JavaScript language but most browser commonly support
them. Example of browser objects are:
 Window object

 History object

 Location object

 Navigator object

 Screen object

Window Object
Represents the browser window. It serves as the global object containing all other
browser objects. You can manipulate the browser window and display dialogs.
Example:
javascript
[Link]("Welcome!"); // Displays an alert box
[Link]([Link]); // Logs the width of the window
History Object
Represents the session history of the browser. It allows navigation through the
history stack.
Example:
javascript
[Link](); // Goes back to the previous page
[Link](); // Goes forward one page
Location Object
Represents the current URL of the browser window. It allows reading parts of the URL
or navigating to new URLs.
Example:
javascript
[Link]([Link]); // Prints full URL
[Link] = "[Link] // Navigates to a new URL
Navigator Object
Provides information about the browser, such as its name, version, platform, and
language.
Example:
javascript
[Link]([Link]); // Browser user-agent string
[Link]([Link]); // Browser language setting
Screen Object
Provides information about the user's screen, such as width, height, and color depth.
Example:
javascript
[Link]([Link]); // Screen width in pixels
[Link]([Link]); // Screen height in pixels

These browser objects enable JavaScript to interact with the browser window, handle
navigation, and adapt to the user's environment efficiently.
1. window Object
The window object is the main object that represents the browser window or tab.
It’s the global object — so all global variables and functions belong to it.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
// [Link]()
[Link]("Hello from window object!");

// [Link] and [Link]


[Link]("Window width: " + [Link]);
[Link]("Window height: " + [Link]);

// You can also access global variables using window


var name = "Payal";
[Link]([Link]); // shows "Payal"
</script>
</body>
</html>
Note: You can write alert("Hello!") instead of [Link]("Hello!") — both work the
same.
2. document Object
The document object represents the HTML page loaded in the browser.
You can use it to read, modify, or create HTML elements.
✅ Example:
<!DOCTYPE html>
<html>
<body>
<h2 id="title">Welcome to JavaScript</h2>
<p id="demo"></p>

<script>
// Change HTML content
[Link]("demo").innerHTML = "Learning Browser Objects";

// Change style
[Link]("title").[Link] = "blue";

// Get page title


[Link]([Link]);
</script>
</body>
</html>

Use document when you want to change or read something from the HTML page.
3. location Object
The location object represents the current URL of the page.
You can use it to get info about the URL, reload, or redirect the user.
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="showLocation()">Show Current URL</button>
<button onclick="reloadPage()">Reload</button>
<button onclick="goToGoogle()">Go to Google</button>

<script>
function showLocation() {
alert("Current URL: " + [Link]);
}

function reloadPage() {
[Link](); // reloads current page
}
function goToGoogle() {
[Link] = "[Link] // redirects
}
</script>
</body>
</html>
Common properties:
 [Link] → full URL

 [Link] → domain name

 [Link] → path of the page

 [Link]() → reloads page

4. history Object
The history object lets you navigate the browser history (back or forward pages).
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="goBack()">Go Back</button>
<button onclick="goForward()">Go Forward</button>

<script>
function goBack() {
[Link](); // Go one page back
}

function goForward() {
[Link](); // Go one page forward
}
</script>
</body>
</html>
Common methods:
 [Link]() → previous page

 [Link]() → next page

 [Link](-1) → also goes back one page

5. navigator Object
The navigator object gives information about the browser and device.
✅ Example:
<!DOCTYPE html>
<html>
<body>
<script>
[Link]("Browser Name: " + [Link]);
[Link]("Browser Version: " + [Link]);
[Link]("User Agent: " + [Link]);
[Link]("Language: " + [Link]);
[Link]("Online: " + [Link]);
</script>
</body>
</html>
Common properties:
 [Link] → browser name

 [Link] → full browser details

 [Link] → browser language

 [Link] → true or false


The Document Object in JavaScript represents the HTML or XML document loaded
into the browser window. It is part of the Document Object Model (DOM) which
allows scripts to dynamically access and update the content, structure, and style of a
web page. The document object is the entry point for accessing the web page
elements and interacting with them.
Common Methods to Access and Manipulate HTML Elements:
 [Link](id) — Returns the element with the specified ID.

 [Link](className) — Returns a collection (array-

like) of elements with the specified class name.


 [Link](tagName) — Returns a collection of elements

with the specified tag name.


 [Link](selector) — Returns the first element matching a CSS

selector.
 [Link](selector) — Returns a NodeList of all elements

matching a CSS selector.


 [Link](tagName) — Creates a new element node of the
specified tag.
 [Link](text) — Creates a text node.
 [Link](text) — Writes HTML or text directly to the document (usually
used during page load).
 [Link](event, function) — Attaches an event listener to the
document.

[Link](id)
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<h2 id="title">Hello World!</h2>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
// Select element by its ID
let element = [Link]("title");
[Link] = "Text changed using getElementById()!";
[Link] = "blue";
}
</script>
</body>
</html>
[Link](className)
<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<p class="demo">Paragraph 1</p>
<p class="demo">Paragraph 2</p>
<button onclick="highlight()">Highlight Paragraphs</button>

<script>
function highlight() {
let elements = [Link]("demo");
for (let i = 0; i < [Link]; i++) {
elements[i].[Link] = "yellow";
}
}
</script>
</body>
</html>
[Link](tagName)
<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<h3>Fruits List</h3>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>
<button onclick="colorItems()">Color All List Items</button>

<script>
function colorItems() {
let items = [Link]("li");
for (let i = 0; i < [Link]; i++) {
items[i].[Link] = "green";
}
}
</script>
</body>
</html>
[Link](selector)
<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
</head>
<body>
<p class="info">This is first paragraph.</p>
<p class="info">This is second paragraph.</p>
<button onclick="changeFirst()">Change First Paragraph</button>
<script>
function changeFirst() {
let firstPara = [Link](".info");
[Link] = "bold";
[Link] = "red";
}
</script>
</body>
</html>
[Link](selector)
<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>
<button onclick="resizeText()">Resize Text</button>

<script>
function resizeText() {
let paras = [Link](".text");
[Link](p => [Link] = "20px");
}
</script>
</body>
</html>

[Link](tagName)
<!DOCTYPE html>
<html>
<head>
<title>createElement Example</title>
</head>
<body>
<button onclick="addDiv()">Create New Element</button>

<script>
function addDiv() {
let newDiv = [Link]("div");
[Link] = "This is a new div created dynamically!";
[Link] = "purple";
[Link](newDiv);
}
</script>
</body>
</html>
[Link](text)
<!DOCTYPE html>
<html>
<head>
<title>createTextNode Example</title>
</head>
<body>
<button onclick="addText()">Add Text Node</button>

<script>
function addText() {
let text = [Link]("This is a text node added dynamically!");
[Link](text);
}
</script>
</body>
</html>

[Link](text)
<!DOCTYPE html>
<html>
<head>
<title>[Link] Example</title>
</head>
<body>
<script>
// Writes directly into the document
[Link]("<h2 style='color:blue;'>This text is added using
[Link]()</h2>");
</script>
</body>
</html>
[Link](event, function)
<!DOCTYPE html>
<html>
<head>
<title>addEventListener Example</title>
</head>
<body>
<button id="btn">Click Me</button>
<script>
let button = [Link]("btn");
[Link]("click", function() {
alert("Button clicked! Event listener working!");
});
</script>
</body>
</html>
The Document object is essential for client-side JavaScript to dynamically interact
with, traverse, and modify web page content, enabling highly responsive and
interactive user experiences.
Unit – 3

Syllabus: -

Introduction to JavaScript: What is DHTML, JavaScript, basics, Variables, String


Manipulations,
Mathematical functions, statements, operators, arrays and functions.
1) What is DHTML?

Dynamic HyperText Markup Language (DHTML) is a combination of Web


development technologies
used to create dynamically changing websites. Web pages may include animation,
dynamic menus and
text effects.
The technologies used include a combination of
✓ HTML
✓ JavaScript or VB Script
✓ CSS and
✓ The document obje ct model (DOM).

HMTL: - Definition html

CSS: - CSS is used to DHTML to control the look and feel of the web page. Stylesheet
define the color
and fonts of text, the background colors and images, and the placement of objects on
the page. Using
Scripting and the DOM, you can change the style of various elements.
Scripts: - Scripts written in either JavaScript or VBScript are the two most common
scriptitng
languages used to activate DHTML. You use a scripting language to control the objects
specifi ed in the
DOM.
DOM: - The Document Object Model(DOM) is one, which allows you to access any
part of your web
page to change it with DHTML. Every part of a web page is specified by the DOM and
using its
consistent nameing conventions you can access them and change their properties.
Features of DHTML: -

• Dynamic content, which allows the user to dynamically change Web page content
• Dynamic positioning of Web page elements
• Dynamic style, which allows the user to change the Web page’s color, font, size or
content
DHTML

1. DHTML stands for Dynamic


HyperText Markup Language.
2. DHTML creates dynamic web pages.
3. DHTML sites will be fast enough upon client -
side technologies.
4. DHTML creates a page with HTML, CSS,
DOM and Scripts called as DHTML.
5. DHTML may contain server side code.
6. DHTML may require connecti ng to a
database as it interacts with user.
7. DHTML files are stored with .dhtm extension.

8. DHTML requires processing from


browser which changes its look and feel. Difference between HTML and DHTML: -

2) Introduction to JavaScript: -

➢ JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a


popular browser
of that time.
➢ The language was initially called LiveScript and was later renamed JavaScript.
➢ There are many programmers who think that JavaScript and Java are the same.
➢ In fact, JavaScript and Java are very much unrelated. Java is a very complex
programming
language whereas JavaScript is only a scripting language .
➢ The syntax of JavaScript is mo stly influenced by the programming language C.

JavaScript: -

➢ JavaScript is a very powerful client -side scripting language .


➢ JavaScript is used mainly for enhancing the interaction of a user with the webpage.

➢ JavaScript is Scripting Language,it is case sensitive. You can write script either in
head or body part.

In other words, you can make your webpage more lively and interactive, with the help
of JavaScript.
JavaScript is also being used widely in game development and Mobile application
development. HTML
1. HTML stands for HyperText Markup
Language.
2. HTML creates static web pages.
3. HTML sites will be slow upon client -side
technologies.
4. HTML creates a plain page without any
styles and Scripts called as HTML.
5. HTML cannot have any server side code.
6. In HTML, there is no need for database
connectivity.
7. HTML files are stored with .htm or .html
extension.
8. HTML does not require any processing
from browser.
Benefits of JavaScript: -

JavaScript has a number of big benefits to anyone who wants to make their Website
Dynamic.
✓ It is widely supported in Web Browsers.
✓ It gives easy access to the document objects and can manipulate most of them.
✓ JavaScript can give interesting animations without that long download times
associated with
many multimedia data types.
✓ Web surfers don’t need a special plug -in to use you scripts.
✓ JavaScript is relatively secure.
✓ JavaScript can read neither from you local hard disk drive nor write to it.
✓ We cannot get a virus infection directly from JavaScript.
Limitations of JavaScript: -

Although JavaScript looks too much advantageous, but it has some limita tions also:

✓ Most scripts rely upon manipulating the elements of the DOM. Support for a
standard set of
objects currently doesn’t exist and access to objects differs from browser to browser.

✓ If your script doesn’t work then you page is useless.


✓ The problems of broken scripts many web surfers disable JavaScript support in
their browser.
✓ Scripts can run slowly and complex scripts can take long time to start up.
3) JavaScript Basics: -

We cannot create the interactive web pages using HTML. Hence JavaScript is designed
to add the
interactivity in the HTML pages. The JavaScript is very much similar to programming
language.
JavaScript originates from a language called LiveScript. JavaScript is platform
independent and can be
run everywhere. JavaScrip t is used for client -side programming.
Let us write the first JavaScript by which some message will be displayed on the web
page.
Example: -
<html>
<head>
<title>My First JavaScript Program</title>
</head>
<body>
<center>
<script type="text/javascript">
[Link]("Welcome to First Page of JavaScript");
</script>
</center>
</body>
</html> Similar to HTML JavaScript program has two sections, head and body. In the
above program, the tag title is used to set title of the web page. In the body section
we hav e use
<center> tag to display the contents at the center of the web page. Here comes an
important part:

<script type = “text/javascript”>

This line tells the web browser that this is the JavaScript. Then comes
[Link](“Welcome to First Page of JavaScript”);

The [Link] is used to display some text on the web page. The text given
within the double
quotes will displayed on the webpage. The script tag is closed by </script> .

Comments in JavaScript: - The JavaScript allows two kinds of comments

1. Single Line Comment - denoted as //.


2. Multi -Line Comment - denoted as /* */.

Example: -

<html>
<head>
<title>Comment in JavaScript</title>
</head>
<body>
<center>
<script type="text/javascript">
[Link]("Below I have some comment statements");
// This is single line comment
/* we can enter some multiline comments
in java script which will not be displayed on web page */
</script>
</center>
</body>
</html>

4) Variabl es:-

The variables are created in order to store some information. This information can be
numeric (or) it
can be string. In the following we have used few variables.

In JavaScript there is specific data type like other programming language. It has type
as var for all
combination of data.

Example: -
<html>
<head>
<title>Variables in JavaScript</title>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
a=2,b=3;
c = a+b;
[Link](“Addition = “+c);
</script>
</body>
</html> Here, addition of two values are stored in variable c and is printed on web
page.
In the above scripting, the variable stores nume ric value. If the variable need to store
string value, string
should be mentioned between double quotes (“string”).

Example: var str1=”Hello”; var str2=”JavaScript”;


5) String Manipulations or String functions in JavaScript: -

String is a collection of c haracters. In JavaScript using string object many useful string
related
functionalities can be exposed off. Some commonly used methods of string object are
concatenating
two strings, converting the string to upper case or lower case, finding the substring of
a give string and
so on. Some of most common string functionalities are listed below,

Method Meaning

1. concat(str)
This method combines two strings. For example, [Link](s2),
concatenation of string s1 with s2.
2. charAt(index -val) This method will return the position of the character specified by
its
index value.
3. length() This function returns the length of the string.
[Link]( ) This function is used to convert the entire lower case letter to
upper
case letter.
[Link]( ) This function is used to convert the entire upper case letter to lower

case letter.
6. valueOf( ) This function is used to display the value of the particular string.
7. substring(begin, end) This function return the substring specified by begin and end.

8. indexOf( ) This function is used to return the index within the calling string
object of the first occurrence of specified value. If not found -1 will
return.

Example: -

<html>
<head>
<title>String Maniputlation</title>
</head>
<body>
<h3 align="Center">String Manipulation</h3>
<h3 align="center">********************</h3>
<script type="text/javascript">
var s1="Welcome";
var s2="Javascript";
[Link]("The First String is "+s1+"<br>");
[Link]("The Second String is "+s2+"<br>");
[Link]("The Concatenation of the string is "+[Link](s2)+"<br>");
[Link]("Character at 5th position in first string :"+[Link](5)+"<br>");
[Link]("Th e Length of the Second string :"+[Link]+"<br>");
[Link]("UpperCase for the first string:"+[Link]()+"<br>");
[Link]("LowerCase for the second string:"+[Link]()+"<br>");
[Link]("Value of second string is :"+[Link] Of()+"<br>");
[Link]("Substring for the first string :"+[Link](3,7)+"<br>");
[Link]("Index value for the s in second string is:"+[Link]("s")+"<br>");
</script>
</body>
</html>
Output: -

6) Mathematical Functions in JavaScript: -

Mathematical functions and values are part of built in javascript object called
“math.h”. All
functions and attributes used in mathematical, must be accessed through this object
only as
[Link] -name( ).

Function Meaning

1. abs(value)
Return the absolute value of the number passed into it.
2. sqrt(value) Returns the square root of the value.
3. ceil(value) Rounds a number upwards to the nearest integer, return it.
4. floor(value) Rounds a number downwards to the nearest integer, return it.
5. pow(value1,value2) Returns the result of raising value to power.
6. min(value1,value2) Returns the smallest value of the two values passed in it.
7. max(value1,value2) Returns the biggest value of the two values pa ssed in it.
8. round(value1,value2)

9. log(value) Returns the result of rounding its argument to the nearest


integer.
Returns the natural logarithmic values to power.
10. sin(value), cos(value), tan(value) Returns sin, cos and tan values to corresponding
methods.
Example: -

<html>
<head>
<title>Mathematical Functions</title>
</head>
<body>
<script type="text/javascript">
[Link]("<b><u>Mathematical Functions</u></b><br><br>");
[Link]("Absoulte value of 4.9 is..."+[Link](4.9)+"<br>");
[Link]("Square Root value for 4 is..."+[Link](4)+"<br>");
[Link]("Ceil value of 9.1 is..."+[Link](9.1)+"<br>");
[Link]("Floor value of 5.9 is..."+[Link](5 .9)+"<br>");
[Link]("3 Power 4 is..."+[Link](3,4)+"<br>");
[Link]("Minimum value from(6,8) is..."+[Link](6,8)+"<br>");
[Link]("Maximum value from(9,10) is..."+[Link](9,10)+"<br>");
[Link]("Round value of 10.5 is..."+Ma [Link](10.5)+"<br>");
[Link]("Log value for 1 is..."+[Link](1)+"<br>");
[Link]("SIN value for 5 is..."+[Link](5)+"<br>");
[Link]("COS value for 5 is..."+[Link](5)+"<br>");
[Link]("TAN value for 5 is..."+[Link](5)+" <br>");

</script>
</body>
</html>
Output: -

7) Statements in JavaScripts: -

➢ A computer program is a list of "instructions" to be "executed" by a computer. In a


programming
language, these programming instructions are called statements .
➢ JavaScript statements are composed of: Values, Operators, Expressions, Keywords,
and Comments.

For example, it is normal to add a semicolon at the end of the executable statement.
[Link](“JavaScript developed by Brendan Eich in 1995”);

Using semicolon, makes it possible to write multiple statements on one line.


1. Conditional Statements: -

Conditional statements are used to perform different actions based on different


conditions.

1. simple if
2. if else
3. if else if
4. nested if
5. switch

1. simple if: - The if statement to specify a block of JavaScript code to be executed if a


condition is
true.
Syntax: -
if (condition)
{
block of code to be executed if the condition is true
}
Example:
var a = 100;
if (a>20)
{
[Link](“a is greater”);
}

2. if else: - The if else statement to specify a block of code to be executed if the


condition is true, true
statement is executed otherwise false statement is executed.
Syntax: -

if (condition)
{
block of code to be executed if the condition is true
}
else
{
block of code to be executed if the condition is false
}

Example: -

var a = 10;
if (a>20)
{
[Link](“a is greater”);
}
else
{

}
[Link](“b is greater”);

3. if else if: - The if else if statement to specify the first condition become true, block
of code
executed otherwise the second condition will be tested. If all condition becomes
false, else part
will be executed.

Syntax: -
if (condition1 )
{
block of code to be executed if condition1 is true
}
else if ( condition2 )
{
block of code to be executed if the condition1 is false and condition2 is true
}
else
{
block of code to be executed if the condition1 is false and condition2 is
false
}

Example: -
var a=100;
if (a>0)
{
[Link](“The number is positive.”);
}
else if(a<0)
{
[Link](“The number is negative.”);
}
else
{
[Link]( “The number is exactly zero ”);
}
4. nested if:- Nested if statements means an if statement inside another if statement.
i.e. if first condition
become true,it checks another condition.

Syntax: -

if (condition1)
{
if(condition2)
{
statement -1
}

else
{
statement -2
}
}
else
{
statement -3
}

Example: -
var a=26;
if (a>17)
{
if (a>59)
{
[Link](“You are eligible to vote and senior citizen”);
}

else
{
[Link](“You are eligible to vote but not senior citizen”);
}
}
else
{
[Link](“You are not eligible to vote”);
}

5. switch: - The switch statement to select one of many blocks of code to be


executed.

Syntax: -
switch(expression )
{
case n:
code block
break;
case n:
code block
break;
default:
code block
}
Example: -

switch (day)
{
case 0:
day = "Sunday" ;
break ;
case 1:
day = "Monday" ;
break ;
case 2:
day = "Tuesday" ;
break ;
case 3:
day = "Wednesday" ;
break ;
case 4:
day = "Thursday" ;
break ;
case 5:
day = "Friday" ;
break ;
case 6:
day = "Saturday" ;
}

2. Looping Statements: -
A loop is a sequence of instruction s that is continually repeated until the condition
is true. Control comes out of the loop statements once condition becomes false.

There are three types of loopi ng statement that are listed below,

1. while loop
2. do while loop and
3. for loop
1. while loop: -

The while statement will execute a block of code while a condition is true..
Syntax: -
while ( condition )
{
code to be executed

}
Example: -
var i=5;
while(i>1)
{

[Link](a);
i=i-1;
}

2. do...while loop: -
The do...while statement will execute a block of code at least once, and then it will
repeat the loop
while a condition is true.
Syntax:
do
{
code to be executed

}while ( condition );
Example: -
var i=5;
do
{

[Link](a);
i=i-1;
} while(i>1);
3. for loop: -

The for statement will execute a block of code a specified number of times

Syntax: -
for (initialization; condition; increment/decrement)
{
code to be executed
}
Example: -
for(i=1;i<=5;i++)
{

[Link](i);

3. Jumping Statements: -
Jumping statements are used to transfer the program’s control from one location
to another, these are set of keywords
which are responsible to transfer program’s control within the same block or from
one function to another.

Four Types of jumping statements that are listed below

1. Break
2. Continue
3. Goto
4. Return

1. Break: - The break is used to terminate the looping (exit from the loop).
Syntax: - break;

Example: -

for(i=1;i<=5;i++)
{
if(i==3)
{
break;
}
[Link](i);
}

2. Continue: - The continue is used to transfer the program’s control at the


beginning of the loop.
Syntax: - continue;

Example: -

for(i=1;i<=5;i++)
{
if(i==3)
{
continue;
}
[Link](i);
}
3. Goto: - The goto statement is used to transfer the program’s control from one
statement to another statement (where
label is defined).

Syntax: - label1:
-------
-------
-------
goto label1; Example: -
first:

second: [Link](“Welcome to “);


goto second;
goto first;

[Link](“JavaScript”);
4. Return: - The Return statement is used to transfer program’s control from called
function to calling function,
it’s secondary task is to carry value from called function to calling function .

Syntax: - return;

Example: -

c = add(a,b); //function call


[Link](c);

function add(a,b)
{
return (a+b); //return value to called function
}

8) Operators in JavaScript: -
An operator is a symbol which operates on a value or a variable. For example: + is an
operator to
perform addition.

There are different types of operator are listed below,

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Increment and Decrement Operator
5. Assignment Operators
6. Conditional Operator (Ternary Operator)
7. Bitwise Ope rators and
8. Special Operators / Miscellaneous operator.
1. Arithmetic Operators: -
Arithmetic operators take numerical values (either literals or variables) as
their operands and return a single numerical value.

We have numeric variable: x = 10 , y = 5 and result .


Operator sign Description Example Results
+ Addition result = x + y result = 15
- Subtraction result = x - y result = 5
* Multiplication result = x * y result = 50
/ Division result = x / y result = 2
% Modulus result = x % y result = 0

Example: -

<script>
var x = 10, y = 5;
[Link]( x + y); // Addition: 15
[Link]( x - y); // Subtraction: 5
[Link]( x * y); // Multiplication: 50
[Link]( x / y); // Division: 2
[Link]( x % y); // Modulus: 0
</script>
2. Comparison Operators: -
Comparison operators are used in logical statements to determine equality or
difference between variables or values.

Operator Name Sign Description


Equal == If both operands are equal, returns true.
Identical equal === If both operands are equal and/or same data type, returns
true.
Not equal != If both operands are not equal, returns true.
Identical not equal !== If both operands are not equal and/or same data type, returns

true.
Greater than > If left operand larger than right operand, return true.
Less then < If left operand smaller than right operand, return true.
Greater than, equal >= If left operand larger or equal than right operand, return true.
Less than, equal <= If left operand smaller or equal than right operand, return true.
Example: -

<script>
[Link](5 == 5); // true
[Link](5 != 10); // true
[Link](5 > 10); // false
[Link](5 < 10); // true
[Link](5 >= 5); // true
[Link](5 <= 5); // true
</script>

3. Logical Operators: -
Logical operators are used to determine the logic between variables or values .
It returns boolean result base on operands.

Operator Name Sign Description


Logical AND && If first operand evaluate and return a true, only that evaluate the
second operand otherwise skips.
Return true if both are must be true, otherwise return false.
Logical OR || Evaluate both operands,
Return true if either both or any one operand true,
Return false if both are false.
Logical NOT ! Return the inverse of the given value result true become false, and
false
become true.

Example: -

<script>
[Link]((5 == 5) && (10 == 10)); // true
[Link](true && false); // false
[Link]((5 == 5) || (5 == 10)); // true
[Link](true || false); // true
[Link](5 && 10); // return 10
[Link](5 || 10); // return 5
[Link](!5); // return false
[Link](!true); // return false
[Link](!false); // return true
</script>

4. Increment and Decrement Operators: -

Increment and decrement operators are unary operators that add or subtract one
from their operand, respectively

We have numeric variable: x = 10 , y = 5 and result .


Operator Name Description Example Results
++ Increment result = x++
result = x
result = ++x result = 10
result = 11
result = 12
-- Decrement result = x --
result = x
result = --x result = 12
result = 11
result = 10

Example: -

<script>
var x = 10, y = 5;
[Link]( x++); // x: 10, x become now 11
[Link]( x); // x: 11
[Link](++ x); // x become now 12, x: 12
[Link]( x--); // x: 12, x become now 11
[Link]( x); // x: 11
[Link]( --x); // x become now 10, x: 10
</script>
5. Assignment Operators: -
JavaScript assignment operators assign values to left operand based on right
operand. equal (=) operators is used to assign a values .
We have numeric variable: x = 10 , y = 5 and result .

Operator Name Sign Description Example Equivalent to Results


Assignment = Assign value from one operand to
another operand value. result = x result = x result = 17
Addition += Addition of operands and finally assign
to left operand. result += x result = result + y result = 22

Similarly, we using subtraction( -=), multiplication(*=),division(/=),modulo(%=) etc,. in


assignment
operator.

Example: -

<script>
var x = 17, y = 5;
var result = x; // Assignment to left operand(result) base on right operand(y).
[Link]( result);
[Link]( result += x);
[Link]( result -= y);
[Link]( result *= y);
[Link]( result /= y);
[Link]( result %= y);
</script>
answer = expression ? answer1 : answer2; // condition ? true : false 6. Conditional
Operators: -
The conditional operator evaluate the first expression(operand), Base on
expression result return either second operand or third operand.
Syntax: -

Example: -
[Link]((10 == 10) ? "Same value" : "different value");

7. Bitwise Operators: -
The B itwise operators evaluate and perform specific bitwise (32 bits either zero
or one) expression.

Operator Name Sign Description


Bitwise AND & Return bitwise AND operation for given two operands.
Bitwise OR | Return bitwise OR operation for given two operands.
Bitwise XOR ^ Return bitwise XOR operation for given two operands.
Bitwise NOT ~ Return bitwise NOT operation for given operand.
Bitwise Shift Left << Return left shift of given operands.
Bitwise Shift Right >> Return right shift of given operands.
Bitwise Unsigned Shift Right >>> Return right shift without consider sign of given
operands.

Example: -

<script>
[Link](5 & 10); // return 0,calculation: 0000 0101 & 0000 1010 = 0000
0000
[Link](5 | 10); // return 15, calculation: 0000 0101 | 0000 1010 = 0000
1111
[Link](5 ^ 10); // return 15, calculation: 0000 0101 ^ 0000 1010 = 0000
1111
[Link](~5); // return -6, calculation: ~ 0000 0101 = 1111 1010

[Link](10 << 2); // return 40, calculation: 0000 1010 << 2 = 0010 1000
[Link](10 >> 2); // return 2, calculation: 0000 1010 >> 2 = 0000 0010
[Link](10 >>> 2); // return 2, calculation: 0000 1010 >>> 2 = 0000 0010
</script>
8. Special Operators: -

The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if -


else.
, Comma Operator allows multiple expressions to be evaluated as single
statement.

delete
Delete Operator deletes a property from the object.

in
In Operator checks if object has the given property

instanceof
checks if the object is an instance of given type

new
creates an instance (object)

typeof
checks the type of object.

void
it discards the expression's return value.

yield
checks what is returned in a generator by the generator's iterator.

9) Array in JavaScript: -

➢ An array is a collection of data elements which can be accessed through a single


variable name. An
array is made up of set of slots (parts) with each slot assigned a single data element.
➢ We can access the data element either sequentially by reading from the slot of the
program or by
their index value.
➢ The data inside an array is ordered because elements are adde d and accessed in
particular order.

Syntax: var variable_name = [ values ];


Example: -
var a = [10,20,30,40,50];
Here var is data type , a is array name and it holds five values.

Memory Representation of Array: -

10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
In JavaScript, array can also holds mixed data type as the following,

Example: -
var a = [101,10.25,”Welcome”,”JavaScript”,1995];

101 10.25 Welcome JavaScript 1995


a[0] a[1] a[2] a[3] a[4]

Here, a[0],a[4] stored integer values a[1] stored floating value and a[2],a[3] stored
string value

Creating an Array: -

JavaScript supports arrays in three different ways,

1. type array -name = [ “values” ];


2. type array -name = new Array ( “values”);
3. type array -name = new Array ( “values”);

Example: -
var day=[“Monday”,”Tuesday”];

The above array stores two elements, each holding a text of string and array elements
are surrounded by
square brackets( [ ] );

The second approach is using new operator, we can allocate memory dynamically for
the arrays.
Example: - var number = new Array(10, 10.25);
The contents of the array is surrounded by parenthesis because they are parameters
through the
constructors of the array object.

In last approach, we can pass the length of an array instead of elements.


Example: - var number = new Array(4);
Adding Elements to an Array: -

If we want to add an item to an array which already full, but javascript simply extends
the array and
insert the new item.

Example: - day[5] = “Friday”; number[3]=100;

Accessing an Array: -

You can refer to a particular element in an array by ref erring to the name of the array
and the index
number. By default, index number starts at ‘0’.

Example:
[Link](day[1]); [Link](day[2]);
Example: -

<html>
<head>
<title>Array</title>
</head>
<body>
<script type="text/javascript">
var data = [10,10.5,"Welcome","to","javascript"];
var i;
[Link]("Elements in array :"+"<br>");

for(i=0;i<[Link];i++)
{
[Link]("data[" +i+ "]="+data[i]+"<br>");
}
</script>
</body>
</html>

Here, [Link] built -in function, which takes automatically length of an array as 4.

10) Function in JavaScript: -

➢ A Function is a piece of code that performs specific task.


➢ We can write the functions in the JavaScript for bringing the modularity in the
script.
➢ Separate functions can be created for each separate task. This helps in finding the
error from the
program efficiently.
➢ We can define the function anywhere in the script either in head or body section or
both .
➢ The standard practic e to define the function in head section and call that function
from the body
section.

The keyword function is used while defining the function.


Syntax: -
function function -name (arglist)
{
----- // body of the function
}

The function -name can be any combination of letters, digit and underscore( _ ). But
the function -name
cannot contain space. The body of function is surrounded by curly braces ‘{ }’.
Output: -
Example1: -

<html>
<head>
<title>Function</title>
<script type = "text/javascript">
funct ion myfunction()
{
[Link]("Welcome to JavaScript Programming Language");
}
</script>
</head>
<body>
<script type="text/javascript">
[Link]("Hello user..." +"<br>");
myfunction();
</script>
</body>
</html>
In the above program, from body section, myfunction() is calls the function and their
respective code is
written in head part.

Similarly, we can pass some arguments to the function. In the following program, we
have passed
arguments to function and returning values fr om function part to called function.

Example 2: -

<html>
<head>
<title>Function</title>
<script type = "text/javascript">
function myfunction1(str1,str2)
{
str = "It was developed by " +str1+" "+str2;
return str;
}
</script>
</head>
<body>
<script type="t ext/javascript">
var str;
[Link]("Welcome to JavaScript Programming Language..." +"<br>");
str=myfunction1("Brendan Eich","in 1995");
[Link](str);
</script>
</body>
</html>
Output: -
Output: -
What is XML?
Extensible Markup Language (XML) lets you define and store data in a shareable
manner. XML supports information exchange between computer systems such as
websites, databases, and third-party applications. Predefined rules make it easy to
transmit data as XML files over any network because the recipient can use those rules
to read the data accurately and efficiently.
Why is XML important?
Extensible Markup Language (XML) is a markup language that provides rules to
define any data. Unlike other programming languages, XML cannot perform
computing operations by itself. Instead, any programming language or software can be
implemented for structured data management.
For example, consider a text document with comments on it. The comments might give
suggestions like these:
Make the title bold
This sentence is a header
This word is the author
Platform-Independent Data Exchange: XML provides a common, standardized,
plain-text format that allows disparate systems, applications, and databases to
communicate and exchange data, regardless of their underlying operating system or
programming language.
Web Services Communication: It serves as the foundational data format for legacy
web services, most prominently with the SOAP (Simple Object Access Protocol)
protocol, defining how messages are structured and transmitted over the internet.
Data Storage and Structuring: XML is used to store and organize structured data.
Many applications use XML for configuration files and to manage content in a logical,
hierarchical manner.
Content Syndication: Formats like RSS (Really Simple Syndication) and Atom,
which power news feeds and blog subscriptions, are built using XML to distribute
updated content efficiently.
Asynchronous Web Applications (AJAX): Historically, XML was the original
method for fetching data in the background of a web page using the XML DOM,
allowing parts of the page to update without a full reload (though JSON is now more
common for this specific use).
Defining Other Markup Languages: XML is a meta-language used to create
specialized markup languages tailored for specific needs, such as XHTML (a stricter
version of HTML), SVG (Scalable Vector Graphics), and MathML.
Introduction php
PHP stands for Hypertext Preprocessor. It is an open-source, widely used
language for web development. Developers can create dynamic and interactive
websites by embedding PHP code into HTML. PHP can handle data processing,
session management, form handling, and database integration. The latest version
of PHP is PHP 8.4.8, released on June 5, 2025.
 A server-side language that generates dynamic content and interacts with

databases, forms, and sessions.


 Supports easy interaction with databases like MySQL, enabling efficient data

handling.
 Runs on multiple operating systems and works with popular web servers like

Apache and Nginx.

You might also like