Unit-3 Lecture-1: Javascript Features Java and Javascript: A Comparison The First Program Aktu Pyqs
Unit-3 Lecture-1: Javascript Features Java and Javascript: A Comparison The First Program Aktu Pyqs
Today’s Target
JavaScript
Introduction
Features
Java and JavaScript: A comparison
The first program – “Hello World”
AKTU PYQs
Web Technology
UNIT – III:
Scripting:
JavaScript: Introduction, documents, forms, statements, functions, objects, Introduction
to AJAX.
Networking:
Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP Client
Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram.
JavaScript
Interactive
Webpage
responds based
on user
actions.
Dynamic
Output
changes when
the inputs
change.
Programming Computing Sum, Subtraction, Multiplication, Division requires program (script) to be written to
implement logic.
JavaScript
Points to note:
The programs in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
JavaScript was created by Brendan Eich at Netscape in 1995. It initially had the name:
“LiveScript” but Java was very popular at that time, so the name was changed to
JavaScript. But JavaScript is a fully independent language with its own specification and
has no relation to Java at all.
JavaScript
Points to note:
Java and JavaScript: A comparison
Java is a general-purpose, compiled language used for building a wide range of
applications, including: Desktop applications, Web servers, Scientific computing and
Android apps.
JavaScript is a scripting language primarily used for creating interactive web pages and
web applications. It can also be used for server-side development with Node.js.
Java is influenced by C++, with a more verbose syntax and strong emphasis on object-
oriented programming (OOP) principles.
JavaScript is influenced by C with a more flexible syntax and support for various
programming paradigms, including OOP, functional, and imperative.
Java is compiled into bytecode, which is then executed by the Java Virtual Machine
(JVM).
JavaScript is interpreted directly by the browser or other runtime environments.
JavaScript
Points to note:
Java is statically typed, meaning the data type of a variable must be declared at compile
time.
JavaScript is dynamically typed, meaning the data type of a variable is determined at
runtime.
JavaScript
Points to note:
JavaScript continues to evolve with each new version of ECMAScript (ES), which
defines the language's capabilities and features. The latest and current 15th version is
ES2024.
JavaScript can execute at client side (in the browser), as well as on the server side, or
actually on any device that has a special program called the JavaScript engine.
The browsers have JavaScript engine embedded in them. Most popular browsers Chrome,
Edge, Firefox, Opera, Safari support JavaScript.
The JavaScript engine parses scripts, converts them into machine code, and executes
them quickly.
JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="output" style="border: 2px solid
red"></div>
<script>
/*document.write("Hello World");*/
// alert("Hello World");
//
document.getElementById("output").innerHTML =
"Hello World";
console.log("Hello World");
</script>
</body>
</html>
UNIT-3 Lecture-2
Today’s Target
JavaScript
Variables
Constants
Datatypes
AKTU PYQs
JavaScript
Variables
Variables are containers for storing data values.
They act as "labels" that hold data which can be used and manipulated in a program.
Before using a variable, you need to declare it.
Variable Declaration
We can declare variables to store data by using the var, or let keywords.
Example: let name; var name; //Old way of declaring variables
name =‘Gateway’; name = ‘Gateway’;
A variable name can be any valid identifier. By default, the variable has a special value
undefined if it is not assigned a value.
Earlier, it was technically possible to create a variable by a mere assignment of the value
without using let/ var. This still works now if we don’t put ‘use strict’ in our scripts to
maintain compatibility with old scripts.
JavaScript
Constants
Variables declared using const are called “constants”. They cannot be reassigned. An
attempt to do so would cause an error.
Example:
const NUM_SUBJECTS = 3;
When a programmer is sure that a variable will never change, they can declare it with
const to guarantee and communicate that fact to everyone.
JavaScript
Datatypes
JavaScript has 8 basic data types:
1. number: For numbers of any kind (integer or floating-point). Integers are limited
by ±(253-1)
Besides regular numbers, there are “special numeric values” which also belong to this data
type: Infinity, -Infinity and NaN. Infinity represents the mathematical Infinity ∞. NaN
represents a computational error. It is a result of an incorrect or an undefined mathematical
operation, for example: “four" / 2.
2. bigint: For integer values of arbitrary length. A BigInt value is created by
appending n to the end of an integer:
1234567890123456789012345678901234567890n;
3. string: For text. A string may contain zero or more characters; there is no separate
single-character type.
JavaScript
Datatypes
7. object: For more complex data structures, such as arrays, functions, and objects
themselves.
8. symbol: For unique identifiers, primarily used for object properties to ensure
uniqueness.
JavaScript
Datatypes
Note: The result of typeof null is "object". That’s an officially recognized historical error
in typeof, operator of JavaScript and kept for compatibility.
null is not an object. It is a special value with a separate type of its own. The behavior of
typeof is wrong here.
JavaScript
Datatypes
Example:
<script>
document.writeln(typeof undefined+"<br>") // "undefined"
document.writeln(typeof 0+"<br>") // "number"
document.writeln(-4/0+"<br>") // "-Infinity"
document.writeln('four'/2+"<br>") // "NaN"
document.writeln(typeof -Infinity+"<br>") // "number"
document.writeln(typeof Infinity+"<br>") // "number"
document.writeln(typeof NaN+"<br>") // "number"
document.writeln(typeof 0+"<br>") // "number"
document.writeln(typeof 20n+"<br>") // "bigint"
document.writeln(typeof true+"<br>") // "boolean"
document.writeln(typeof "Gateway"+"<br>") // "string"
document.writeln(typeof Symbol("symbol1")+"<br>") // "symbol"
document.writeln(typeof document+"<br>") // "object"
document.writeln(typeof null+"<br>") // "object"
document.writeln(typeof alert+"<br>") // "function"
</script>
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<head>
<title>Variables in JavaScript</title>
<script>
let message;
message="Amol"
document.write(message);
if (true) {
let a=10;
}
document.write("<br>")
// document.write(a)
document.write(b);
let b=10;
</script>
</head>
<body>
</body>
</html>
DataTypesDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Datatypes in JavaScript</title>
<script>
document.write(typeof 0+"<br>");
document.writeln(typeof undefined);
document.write("<br>");
document.write(typeof 34n);
document.write("<br>");
document.write(typeof true);
document.write("<br>");
document.write(typeof('Gateway'));
document.write("<br>");
document.write(typeof Infinity);
document.write("<br>");
document.write(-4/0);
document.write("<br>");
document.write(4/0);
document.write("<br>");
document.write("four"/0);
document.write("<br>");
document.write(typeof NaN)
document.write("<br>");
document.write(typeof null);
document.write("<br>");
document.write(typeof document);
document.write("<br>");
document.write(typeof Symbol("mytype"));
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-3
Today’s Target
JavaScript Operators
Arithmetic,
Comparison,
Logical,
Assignment,
Bitwise,
Conditional,
Nullish Coalescing
AKTU PYQs
JavaScript
Operators
In JavaScript, an operator is a symbol used to perform operations on one or more operands,
such as variables or values, and it produces a result.
For example, in the expression 4 + 5, 4 and 5 are operands, while + is the operator that adds
them, resulting in 9.
Arithmetic Operators
Arithmetic operators in JavaScript perform mathematical calculations on numeric values
(operands). Most arithmetic operators are binary operators, means that they perform calculations
on two operands. However, some arithmetic operators are unary, meaning they operate on just a
single operand.
JavaScript
Operators
Arithmetic Operators
Operators
Comparison Operators
In JavaScript, comparison operators are used to compare two variables or values, resulting in a
boolean value of either true or false based on the outcome.
For instance, comparison operators help determine if two operands are equal.
These operators are commonly used within logical expressions, which evaluate to either
true or false.
Comparison operators are binary, meaning they operate on two operands. The operands
can be numbers, strings, booleans, or objects.
JavaScript
Operators
Comparison Operators
!= Unequal Checks if two values are not equal, allowing type conversion.
Checks if two values are equal and of the same type (strict
=== Strictly equal
equality).
Checks if two values are not equal or not of the same type
!= = Strictly unequal
(strict inequality).
> Greater than Checks if the left value is greater than the right value.
< Less than Checks if the left value is less than the right value.
Checks if the left value is greater than or equal to the right
>= Greater than or Equal to
value.
<= Less than or Equal to Checks if the left value is less than or equal to the right value.
JavaScript
Operators
Logical Operators
Logical operators in JavaScript are symbols that help you make decisions in code by checking
whether conditions are true or false. They allow you to test multiple conditions at once or reverse
a condition's true/false value.
Logical operators are primarily used with Boolean values, returning a Boolean result.
While logical operators are mainly used with Boolean values, they can operate on any
data type. Non-Boolean values are converted to Boolean:
"falsy" values convert to false, and
"truthy" values convert to true.
JavaScript
Operators
Logical Operators
JavaScript recognizes six falsy values:
false, null, undefined, 0, "" (empty string), and NaN.
All other values, such as non-zero numbers and non-empty strings, are considered
truthy.
Operators
Assignment Operators
The assignment operators in JavaScript are used to assign values to the variables. These are
binary operators. An assignment operator takes two operands, assigns a value to the left operand
based on the value of right operand.
Operators
Bitwise Operators
The bitwise operators in JavaScript perform operations on the integer values at the binary level.
Bitwise operators are similar to logical operators but they work on individual bits. Bitwise
operators work on 32-bits operands.
Operator Name Description
Operators
Conditional Operator ( ? : )
The conditional operator in JavaScript first evaluates an expression for a true or
false value and then executes one of the two given statements depending upon the
result of the evaluation. The conditional operator is also known as the ternary
operator.
Syntax condition ? exp1 : exp2;
− If is condition true, exp1 is executed else exp2 is executed.
Example:
let num1=30;
let num2=4;
document.write(num1>num2 ? num1 : num2);
JavaScript
Operators
Nullish coalescing operator (??)
It returns the first operand if it’s not null/undefined. Otherwise, the second one.
Syntax operand1 ?? operand2;
Example 1:
let user;
alert(user ?? "Anonymous"); // Anonymous (user is undefined)
Example 1:
let user = "John";
alert(user ?? "Anonymous"); // John (user is not null/undefined)
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operators in
JavaScript</title>
<script>
let x=7,y=5;
document.write("<h1 style='font-
weight:bold; color: Green; text-decoration-line:
underline'>Arithmetic Operators</h1>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Addition</p>");
document.write(x+y+"<br>");
document.write(x+"4"+"<br>");
document.write(x+"Four"+"<br>");
document.write("Five"+"Four"+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Subtraction</p>");
document.write(x-y+"<br>");
document.write(x-"4"+"<br>");
document.write(x-"Four"+"<br>");
document.write("5"-"4"+"<br>");
document.write("Five"-"Four"+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Multiplication</p>");
document.write(x*y+"<br>");
document.write(x*"4"+"<br>");
document.write(x*"Four"+"<br>");
document.write("5"*"4"+"<br>");
document.write("Five"*"Four"+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Division</p>");
document.write(x/y+"<br>");
document.write(x/"4"+"<br>");
document.write(x/"Four"+"<br>");
document.write("5"/"4"+"<br>");
document.write("Five"/"Four"+"<br>");
document.write(x/0+"<br>");
document.write(0/0+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Modulus</p>");
document.write(x%y+"<br>");
document.write(x%"4"+"<br>");
document.write(x%"Four"+"<br>");
document.write("5"%"4"+"<br>");
document.write("Five"%"Four"+"<br>");
document.write(x%0+"<br>");
document.write(0%0+"<br>");
document.write(-20/9+"<br>");
document.write(20/-9+"<br>");
document.write(-20%9+"<br>");
document.write(20%-9+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Increment</p>");
document.write(x +" (Value of x) <br>");
document.write(++x +" (Pre Increment)
<br>");
document.write(x++ +" (Post Increment)
<br>");
document.write(x +" (Value of x) <br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Decrement</p>");
document.write(x +" (Value of x) <br>");
document.write(--x +" (Pre Decrement)
<br>");
document.write(x-- +" (Post Decrement)
<br>");
document.write(x +" (Value of x) <br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Exponentiaion</p>");
document.write((2**3)+" (2**3) <br>");
document.write((2**3**2)+" (2**3**2)
<br>");
document.write(("2"**"3")+" (2**3)
<br>");
document.write(("2"**"Three")+"
(2**Three) <br>");
document.write((2**[])+" (2**[]) <br>");
document.write((2**[2])+" (2**[2])
<br>");
</script>
</head>
<body>
</body>
</html>
ComparisonOperatorsDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Comparison Operators in
JavaScript</title>
<script>
let a=10, b=20;
document.write("<h1 style='font-
weight:bold; color: Green; text-decoration-line:
underline'>Comparison Operators</h1>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Equal</p>");
document.write((a==b)+"<br>");
document.write((a==10)+"<br>");
document.write((10==10)+"<br>");
document.write((10=="10")+"<br>");
document.write((0==false)+"<br>");
document.write((0=='')+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Unequal</p>");
document.write((a!=b)+"<br>");
document.write((a!=10)+"<br>");
document.write((10!=10)+"<br>");
document.write((10!="10")+"<br>");
document.write((0!=false)+"<br>");
document.write((0!='')+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Strictly equal</p>");
document.write((a===b)+"<br>");
document.write((a===10)+"<br>");
document.write((10===10)+"<br>");
document.write((10==="10")+"<br>");
document.write((0===false)+"<br>");
document.write((0==='')+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Strictly unequal</p>");
document.write((a!==b)+"<br>");
document.write((a!==10)+"<br>");
document.write((10!==10)+"<br>");
document.write((10!=="10")+"<br>");
document.write((0!==false)+"<br>");
document.write((0!=='')+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Greater than</p>");
document.write((a>b)+"<br>");
document.write((a>10)+"<br>");
document.write((10>6)+"<br>");
document.write((10>"6")+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Less than</p>");
document.write((a<b)+"<br>");
document.write((a<10)+"<br>");
document.write((10<60)+"<br>");
document.write((10<"60")+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Greater than Equal to</p>");
document.write((a>=b)+"<br>");
document.write((a>=10)+"<br>");
document.write((10>=6)+"<br>");
document.write((10>="6")+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Less than Equal to</p>");
document.write((a<=b)+"<br>");
document.write((a<=10)+"<br>");
document.write((10<=60)+"<br>");
document.write((10<="60")+"<br>");
</script>
</head>
<body>
</body>
</html>
LogicalOperatorsDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Logical Operators in
JavaScript</title>
<script>
document.write("<h1 style='font-
weight:bold; color: Green; text-decoration-line:
underline'>Logical Operators</h1>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Logical AND</p>");
document.write((true && false)+"<br>");
document.write((false && true)+"<br>");
document.write((false && false)+"<br>");
document.write((true && true)+"<br>");
document.write((0 || 7)+"<br>");
document.write((7 || 0)+"<br>");
document.write((6 || 7)+"<br>");
document.write((0 || 0)+"<br>");
document.write((undefined || 7)+"<br>");
document.write((7 || null)+"<br>");
document.write((NaN || 7)+"<br>");
document.write(('' || 0)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Logical NOT</p>");
document.write(!(true && false)+"<br>");
document.write(!(false && true)+"<br>");
document.write(!(false && false)+"<br>");
document.write(!(true && true)+"<br>");
document.write(!(0 || 7)+"<br>");
document.write(!(7 || 0)+"<br>");
document.write(!(6 || 7)+"<br>");
document.write(!(0 || 0)+"<br>");
</script>
</head>
<body>
</body>
</html>
AssignmentOperatorsDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Assignment Operators in
JavaScript</title>
<script>
let x;
let y;
document.write("<h1 style='font-
weight:bold; color: Green; text-decoration-line:
underline'>Assignment Operators</h1>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Assignment</p>");
x=4;
y=2;
document.write("x= "+x+"<br>");
document.write("y= "+y+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Addition Assignment</p>");
document.write("After (x+=y), x=
"+(x+=y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Subtraction Assignment</p>");
document.write("After (x-=y), x= "+(x-
=y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Multiplication Assignment</p>");
document.write("After (x*=y), x=
"+(x*=y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Division Assignment</p>");
document.write("After (x/=y), x=
"+(x/=y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Remainder Assignment</p>");
document.write("After (x%=y), x=
"+(x%=y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Exponentiation Assignment</p>");
document.write("After (x**=y), x=
"+(x**=y)+"<br>");
</script>
</head>
<body>
</body>
</html>
BitwiseOperatorsDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Bitwise Operators in
JavaScript</title>
<script>
let x;
let y;
document.write("<h1 style='font-
weight:bold; color: Green; text-decoration-line:
underline'>Bitwise Operators</h1>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Bitwise AND</p>");
x=4;
y=2;
document.write("x (4: 0100) & y (2:
0010): "+(x&y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Bitwise OR</p>");
document.write("x (4: 0100) | y (2:
0010): "+(x|y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Bitwise XOR</p>");
document.write("x (4: 0100) ^ y (2:
0010): "+(x^y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Bitwise NOT</p>");
document.write("~y (2: 0010):
"+(~y)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Left Shift</p>");
document.write("(x<<2), x=
"+(x<<2)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Right Shift</p>");
document.write("(x>>2), x=
"+(x>>2)+"<br>");
document.write("<p style='font-
weight:bold; color: blue; text-decoration-line:
underline'>Right Shift with Zero</p>");
document.write("(x>>>2), x=
"+(x>>>2)+"<br>");
let z=4;
document.write(z??"z not defined");
</script>
</head>
<body>
</body>
</html>
ConditionNullishCoalescingOperatorsDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Conditional and Nullish Coalescing
Operators</title>
<script>
let a=10;
let b=20;
//Conditional Operator
document.write(a<b?a:b)
let num=10;
document.write("<br>")
//Nullish Coalescing
document.write(num??"Undefined Value")
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-4
Today’s Target
JavaScript
Statements
Sequential Statements
Conditional (Alternating) Statements
Iteration (Looping) Statements
AKTU PYQs
JavaScript
Statements
Declaration Statements:
Define variables and constants that hold values or references.
Example var name = “Gateway"; // Declares a variable using 'var’
let age = 25; // Declares a variable using 'let’
const PI = 3.14; // Declares a constant using 'const’
Expressions
Perform calculations, assignments, or call functions.
Example let x = 5 + 10; // Addition and assignment
document.write(x); / Function call
JavaScript
Statements
Conditional (Alternating) Statements
Conditional statements are used when we need to perform different actions based on different
conditions.
Conditional statements allow the execution of different blocks of code based on certain
conditions.
They help control the flow of a program by making decisions.
‘if’ statement:
The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a
block of code.
Example let percentAtt = 76;
if (percentAtt >= 75) {
document.write(“You are allowed to appear in exams.");
}
JavaScript
Statements
Conditional (Alternating) Statements
‘if...else’ Statement:
The if statement may contain an optional else block. It executes when the if condition is
false.
Example let percentAtt = 76;
if (percentAtt >= 75) {
document.write(“You are allowed to appear in exams.");
}
else {
document.write(“You are not allowed to appear in exams.");
}
JavaScript
Statements
Conditional (Alternating) Statements
‘else...if’ Statement (several conditions):
‘else...if’ statement is used to test several variants of a condition.
Example
let i = 0;
do {
document.write( i );
i++;
} while (i < 3);
JavaScript
Statements
Iteration (Looping) Statements
‘for’ loop
This loop, repeatedly executes a block of code a specified number of times, based on an
initialization, a condition to evaluate at each iteration, and a step to update the loop counter.
Example
for (let i = 3; i > 0; i--) {
alert(i);
}
initialization let i = 3 Executes once upon entering the loop.
condition i>0 Checked before every loop iteration. If false, the loop stops.
body alert(i) Runs again and again while the condition is truthy.
step i-- Executes after the body on each iteration.
let course= { name: "Web Technology", let courses = ["WT", "DAA", "DBMS"];
code: "BCS 502" };
Example 1 Example 2
<!DOCTYPE html>
<html>
<head>
<title>Statements in JavaScript</title>
<script>
let a=100;
let b=100;
if(a<b){
document.write("a is less than b");
}
else if (a==b) {
document.write("a is equal to b");
}
else {
document.write("a is greater than
b");
}
document.write("<br>")
let variab=0;
if(variab)
document.write("Gateway");
else
document.write("classes");
document.write("<br>");
let day=6;
switch(day){
case 1: document.write("Monday");
break;
case 3: document.write("Wednesday");
break;
case 5: document.write("Thursday");
break;
default: document.write("Value is
other than 1,3, & 5!")
}
document.write("<br>")
let aVar=1;
while(aVar<3)
{
document.write(aVar+"<br>");
aVar++;
}while(aVar<3);
aVar=3;
do
{
document.write(aVar+"<br>");
aVar++;
}while(aVar<3);
let i=0;
for(;i<3;i++)
{
document.write(i+"<br>");
}
programs = {
name:"B.Tech.",
code:"10"
}
document.write("<br>")
for(let i=23;i<45;i++)
{
if(i==30)
continue;
if(i==40)
break;
if(i%2==0)
document.write(i+"<br>");
}
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-5
Today’s Target
JavaScript
Functions
Function Declaration
Returning values
Default values for parameters
Function Expressions
Arrow Functions
AKTU PYQs
JavaScript
Functions
Functions are the main “building blocks” of the program. Functions allow to perform a
similar action in many places of the script.
They allow the code to be called many times without repetition i.e. they avoid code duplication.
Function Declaration
Function declaration is used to create a function in JavaScript. In a function declaration,
First we write the function keyword then
the name of the function, after it
a list of parameters between the parentheses (comma-separated, or empty) and finally
the code of the function, also named “the function body”, between curly braces.
Examples:
function show() { function showCourse(course) {
document.write("Web Technology"); document.write(course);
} }
show(); showCourse("DBMS");
JavaScript
Functions
A local variable is one that is declared inside a function. It is only visible inside that function.
An outer variable is one that is declared outside a function. A function can access an outer
variable as well. Variables declared outside of any function, are called global variables.
If a same-named variable is declared inside the function then it shadows the outer one.
Global variables are visible from any function (unless shadowed by locals).
Example:
let outerGlobal = 10; function print2() {
document.write(outerGlobal);
let inner=20;
//Output: 40, print1() changes it to 40
function print1() {
} print2();
inner=30;
document.write(outerGlobal); //Output: 10
outerGlobal=40;
document.write(inner);
//Output: 30, local variable shadowed outer.
}
print1();
JavaScript
Functions
Returning a value from function
A function can return a value back into the calling code.
Example:
function add(a, b){
return a+b;
}
document.write(add(5,6)) //Output: 11
The ‘return’ can be in any place of the function. When the execution reaches it, the function
stops, and the value is returned to the calling code.
There may be many occurrences of return in a single function.
It is possible to use return without a value. That causes the function to exit immediately.
A function with an empty return or without it returns undefined
Never add a newline between return and the value. It will not work, because JavaScript will
assume a semicolon after return in this case.
JavaScript
Functions
Default values for parameters
If a function is called, but an argument is not provided, then the corresponding value becomes
undefined.
We can specify our own default values for parameters in the function declaration, using =.
Example:
function add(a, b=5){
return a+b;
}
document.write(add(5,6)) //Output: 11, as a=5, and b=6
document.write(add(5)) //Output: 10, as a=5, and b=5
document.write(add()) //Output:NaN, as a=undefined, and b=5
<!DOCTYPE html>
<html>
<head>
<title>Functions in JavaScript</title>
<script>
function multiply(a=5,b=8) {
return a*b;
}
document.write(multiply(4,5))
document.write(multiply(4))
document.write(multiply())
document.write("<br>"+doubles(4))
//Function Declaration
function doubles(num){
return num*2;
}
//Function Expression
let doubleNum = function(num) {
return num*2;
};
document.write("<br>"+doubleNum(7))
document.write("<br>")
document.write(doubleNum)
document.write("<br>")
document.write(doubleNum(6))
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-6
Today’s Target
JavaScript
Popup Dialog Boxes
alert
confirm
prompt
AKTU PYQs
JavaScript
In JavaScript, a popup dialog box is a small, temporary window that appears on the current
web page to convey a message or interact with the user.
JavaScript provides three main types of popup dialog boxes: alert, confirm, and prompt.
alert, confirm, and prompt are built-in functions of the window object, that are directly
accessible in the script.
Each dialog box demands user action, making them effective for obtaining input,
confirmations, or alerting users before proceeding with further code.
These dialog boxes temporarily halt execution of the script until the user interacts with them,
ensuring any subsequent actions wait for user input.
JavaScript
‘confirm’ box
The function confirm shows a window with a question and two buttons: OK and Cancel.
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Example: confirm(“Do you want to delete the file?");
JavaScript
<script>
let num = prompt("Input a number");
document.write(typeof num)
let isConfirm = confirm("Your input is "+num);
if(isConfirm)
alert("The double of "+num+" is "+num*2);
</script>
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<head>
<title>Popup Dialog Boxes in
JavaScript</title>
<script>
let course = prompt("Input a
course","TAFL")
document.write(typeof course)
let isConfirmed = confirm("The input you
have given is "+course+" Are you sure?")
document.write(typeof isConfirmed)
if(isConfirmed)
alert("You selected the course
"+course+" to study.")
</script>
</head>
<body>
</body>
</html>
Program1.html
<!DOCTYPE html>
<html>
<head>
<title>PYQ - Program 1</title>
<script>
function compareNums(a,b,c,d) {
if(a>b && c>d)
alert(true);
else
alert(false);
}
compareNums(2,3,4,5);
compareNums(5,4,3,2);
</script>
</head>
<body>
<p>Question: Outline a JS function that takes
4 variables, a, b, c, d, and prints true in an
alert box
if input a > input b and input c > input
d. Else, print false in an alert box.
</p>
</body>
</html>
UNIT-3 Lecture-7
Today’s Target
JavaScript
Arrays
Creating and accessing elements
‘length’ property and Array Methods
Iterating through Arrays
Multidimensional Arrays
AKTU PYQs
JavaScript
Arrays
An array is a special type of object in JavaScript that can hold multiple values in a single
container.
Arrays allow us to store a collection of elements under a single name.
Arrays are objects with indexed elements, making them different from traditional arrays in
other languages.
Elements are ordered and indexed, starting at 0.
Arrays can store different types of data in each element (e.g., numbers, strings, objects).
They are dynamic, meaning their size can grow or shrink as needed.
JavaScript
Arrays
Creating an Array
Using square brackets
Example: let fruits = ["apple", "banana", "cherry"];
Array Methods
push(): Adds one or more elements to the end of an array and returns the new length.
Example: arr.push(40); // Adds 40
pop(): Removes the last element of the array and returns it.
Example: arr.pop(); // Removes 40
JavaScript
Arrays
Array Methods
shift(): Removes the first element of the array and returns it.
Example: arr.shift(); // Removes 10
unshift(): Adds one or more elements to the beginning of an array and returns the new length.
Example: arr.unshift(5); // Adds 5
indexOf(): Returns the first index of a specified value in the array, or -1 if not found.
Example: arr.indexOf(20); // Output: 1
includes(): Checks if the array contains a specified value and returns true or false.
Example: arr.includes(30); // Output: true
JavaScript
Arrays
Array Methods
join(): Joins all array elements into a string separated by a specified delimiter.
Example: arr.join("-"); // Output: "10-20-30"
JavaScript
Arrays
Array Methods
reverse(): Reverses the order of elements in the array.
Example: arr.reverse(); // [30, 20, 10]
sort(): Sorts the elements of the array in place and returns the sorted array.
Example: arr.sort(); // Default: Lexicographical sorting, elements are sorted as strings.
To use our own sorting order, we need to supply a function as the argument of sort().
Example: arr.sort((a,b)=>a-b); //Soring will be done as per the comparison function
map(): Creates a new array with the results of calling a function on every element.
Example: let squared = arr.map(x => x * x); // Squares each element
forEach(): Executes a function on each array element without returning a new array, unlike
map(), which returns a new transformed array.
Example: arr.forEach(num => document.write(num * 2)) //Writes double of each array
element on the document.;
JavaScript
Arrays
Array Methods
filter(): Creates a new array with all elements that pass a test implemented by a function.
Example: let even = arr.filter(x => x % 2 === 0); // Filters even numbers
reduce(): Executes a reducer function on each element and returns a single result.
Example: let sum = arr.reduce((a, b) => a + b, 0); // Sums elements
at(): allows to access elements in an array using both positive and negative indexes, where
negative indexes count from the end of the array.
Example: arr.at(-2); // returns second last element from the array.
<!DOCTYPE html>
<html>
<head>
<title>Arrays in JavaScript</title>
<script>
let arr = [23, 45, 89, 93, "WT",false];
document.write(arr);
document.write("<br>"+arr.length);
document.write("<br>"+arr[4]);
document.write("<br>"+arr.push(12))
document.write("<br>"+arr);
document.write("<br>"+arr.pop())
document.write("<br>"+arr);
document.write("<br>"+arr.unshift(4,5))
document.write("<br>"+arr);
document.write("<br>"+arr.shift())
document.write("<br>"+arr)
arr[5]=45;
document.write("<br>"+arr)
arr[6]=45;
document.write("<br>"+arr)
document.write("<br>"+arr.indexOf(45))
document.write("<br>"+arr.lastIndexOf(45)
)
document.write("<br>"+arr.includes(23))
document.write("<br>"+arr.includes("WT"))
arr.splice(2,1,56,33,9);
document.write("<br>"+arr);
document.write("<br>"+arr.slice(3,6))
document.write("<br>"+arr.concat(arrToCon
cat))
document.write("<br>"+arr)
document.write("<br>"+arr.join("-"))
document.write("<br>"+arr.reverse())
document.write("<br>"+arr)
document.write("<br>"+arr.sort())
document.write("<br>"+arr.sort((a,b)=>a-
b))
document.write("<br>"+arr.map((num)=>num+
3))
document.write("<br>")
document.write(arr)
document.write("<br>")
arr.forEach((num)=>document.write("-
>"+(num-3)))
document.write("<br>"+arr.filter((num)=>n
um%2==0))
let arrToSum = [1,2,3]
document.write("<br>"+arrToSum.reduce((a,
b)=>a+b))
document.write("<br>"+arr.find((num)=>num
<10))
document.write("<br>"+arr.findIndex((num)
=>num<10))
let a=5
document.write("<br>"+Array.isArray(a))
document.write("<br>"+Array.isArray(arr))
document.write("<br>"+arr.every((num)=>nu
m>4))
document.write("<br>"+arr.every((num)=>nu
m>10))
document.write("<br>"+arr.at(-4))
document.write("<br>"+arr.toString())
document.write("<br>"+arr)
document.write("<br>")
for(let i=0;i<arr.length;i++)
document.write(arr[i])
document.write("<br>")
for(let element of arr)
document.write(element)
let threedarr =
[
[[1,2],[3,4],[5,6]],
[[7,8],[9,10],[11,12]]
]
document.write("<br>"+threedarr[1][0][1])
document.write("<br>")
for(let x of threedarr){
for(let y of x) {
for(let z of y)
document.write(z)
}
}
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-8
Today’s Target
JavaScript
‘document’ Object
Properties
Methods
Writing on the document
Manipulating DOM Elements
Creating, Adding, and Removing DOM Elements
AKTU PYQs
JavaScript
‘document’ Object
The document object in JavaScript provides access to all elements of an HTML document. It
acts as an interface to the Document Object Model (DOM), allowing JavaScript to access and
manipulate HTML document dynamically.
The document object includes various properties and methods that allow you to retrieve
information about HTML elements and dynamically modify them.
In JavaScript, the document object is a property of the window object. You can access it using
the window.document syntax, but it is also accessible directly without prefixing it with the
window object as window is a global object.
JavaScript
‘document’ Object
Properties
document.documentElement
Refers to the <html> element of the document and used to access or manipulate the root
element of the document.
Example: document.write(document.documentElement);
document.head
Refers to the <head> element of the document and allows access to or manipulation of
the <head> section of the HTML.
Example: document.write(document.head);
document.title
Represents the title of the HTML document and used to get or set the title using this
property.
Example: document.write(document.title);
document.title = “Gateway Classes"; // Changes the title
JavaScript
‘document’ Object
Properties
document.body
Refers to the <body> element of the document and allows access to or modification of the
content within the <body> tag.
Example: document.write(document.body);
document.URL
Provides the complete URL of the document currently loaded.
Example: document.write(document.URL);
JavaScript
‘document’ Object
Methods
document.getElementById(id)
Returns a single element with the specified value of the id attribute. It is used to access a
unique element directly.
Example: let element = document.getElementById("myId");
document.getElementsByClassName(className)
Returns a live HTMLCollection of elements with the specified class name. It is used to
access multiple elements sharing the same class.
Example: let elements = document.getElementsByClassName("myClass");
JavaScript
‘document’ Object
Methods
document.getElementsByTagName(tagName)
Returns a live HTML collection of elements with the specified tag name. It is used to access
all elements of a specific type, e.g., all <div> or <p> elements.
Example: let paragraphs = document.getElementsByTagName("p");
document.getElementsByName(name)
Returns all the elements with the specified value of the name attribute. It is commonly used
for form elements like <input> or <select>.
Example: let inputs = document.getElementsByName("username");
Note: All these methods (except getElementsByName) return live collections, meaning they
update automatically if the DOM changes.
JavaScript
‘document’ Object
Methods
querySelector(selector)
Selects the first element in the DOM that matches the specified CSS selector.
Example: let firstItem = document.querySelector("li.active");
querySelectorAll(selector)
Selects all elements in the DOM that match the specified CSS selector
Example: let allButtons = document.querySelectorAll("p");
Note:
Both querySelector and querySelectorAll are versatile methods that provide a modern
and powerful way to access elements compared to traditional getElementBy... methods.
They support any valid CSS selectors like .class, #id, [attribute], pseudo-classes, etc.
JavaScript
‘document’ Object
Writing on the document
document.write():
Writes the given HTML content or text directly to the document.
document.writeln():
Writes the given HTML content or text directly to the document and adds a new line
at the end.
Example:
document.write("<pre>") document.write("<pre>")
document.write("Hello") document.writeln("Hello")
document.write("World") document.writeln("World")
document.write("</pre>") document.write("</pre>")
Browsers treat multiple spaces or newline characters in HTML as a single space when rendering content. This is why
the \n from writeln() doesn’t visibly change the layout. The <pre> tag, used above in the example, preserves spaces
and newlines in the output, making the effect of writeln() clear.
JavaScript
‘document’ Object
Manipulating DOM Elements
Changing Content
innerHTML:
This property retrieves or sets the HTML content (including tags) of an element.
Example: let element=document.getElementById(“para1”);
element.innerHTML = "<b>Hello World!</b>";
textContent:
This property retrieves or sets the plain text content of an element without any tags.
Example: element.textContent = "Hello World!";
Changing Styles
style:
This property is used to access or set inline CSS styles directly on an element.
Example: element.style.backgroundColor = "blue";
JavaScript
‘document’ Object
Manipulating DOM Elements
Changing Attributes
setAttribute:
Sets the value of a specified attribute on an element.
Example: let element = document.getElementsByTagName("img")[0]
element.setAttribute("src", "image.jpg");
getAttribute:
Retrieves the value of a specified attribute on an element.
Example: element.getAttribute("src");
JavaScript
‘document’ Object
Creating, Adding, and Removing Elements in the DOM
appendChild():
Adds a new child element to the end of a parent element.
Example: parentElement.appendChild(newDiv);
insertBefore():
Inserts a new element before a specified child element.
Example: parentElement.insertBefore(newDiv, existingChild);
JavaScript
‘document’ Object
Creating, Adding, and Removing Elements in the DOM
removeChild():
Removes a child element from its parent.
Example: parentElement.removeChild(childElement);
replaceChild():
Replaces an existing child element with a new one.
Example: parentElement.replaceChild(newDiv, oldChild);
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<head>
<title>document Object in JavaScript</title>
</head>
<body>
<p id="para1" class="para">Document
Object</p>
<p class="para">in JavaScript</p>
<form>
<input type="text" name="course">
</form>
<script>
document.write(document.title)
document.title="JavaScript 'document'
object"
document.write("<br>")
document.write(document.documentElement.t
agName)
document.write("<br>")
document.write(document.head.tagName)
document.write("<br>")
document.write(document.body.tagName)
document.write("<br>")
document.write(document.URL)
document.write("<br>")
// let elements =
document.getElementsByTagName("p");
// let paraElement = elements[0]
// paraElement.innerHTML = "Document
Object in JavaScript"
// paraElement =
document.getElementById("para1")
// paraElement.innerHTML ="<b>We are
studying about 'document' object.</b>"
let elements =
document.getElementsByClassName("para")
let paraElement1 = elements[0]
let paraElement2 = elements[1]
paraElement1.innerHTML = "Amol"
paraElement2.innerHTML = "Sharma"
let
textField=document.getElementsByName("course")[0]
document.write(textField.tagName)
textField.setAttribute("placeholder","Ent
er course here...")
document.querySelector(".para").innerHTML
="Gateway"
document.querySelectorAll(".para")[1].inn
erHTML="Classes"
document.write(paraElement2.textContent)
paraElement2.textContent = "Sharma"
paraElement2.style.color = "lightblue"
document.write(textField.getAttribute("ty
pe"))
let divElement =
document.createElement("div")
divElement.style.width="100px"
divElement.style.height="100px"
divElement.style.border="1px solid black"
document.body.appendChild(divElement)
let paragraph1 =
document.createElement("p")
paragraph1.textContent="JavaScript"
divElement.appendChild(paragraph1)
let paragraph2 =
document.createElement("p")
paragraph2.textContent="We are studying "
divElement.insertBefore(paragraph2,
paragraph1)
//divElement.replaceChild(paragraph2,
paragraph1)
divElement.removeChild(paragraph2)
document.write("<pre>")
document.write("Gateway")
document.write("Classes")
document.write("</pre>")
document.write("<pre>")
document.writeln("Gateway")
document.writeln("Classes")
document.write("</pre>")
</script>
</body>
</html>
UNIT-3 Lecture-9
Today’s Target
JavaScript
Forms
Accessing form & its elements
Using properties of form elements
Form Events
Form validation
AKTU PYQs
JavaScript
Forms
Forms enable the users to interact with the web page dynamically and/or to submit data to the
server for processing.
Forms
Accessing form & its elements in JavaScript
We access form elements in JavaScript to dynamically manipulate, validate, or retrieve input
values from forms.
Accessing Forms
We may access forms by their index or name.
Examples: let form = document.forms.myForm // Uses Name
let form = document.forms[0] // Uses Index
Accessing Elements of Form
We may access form elements by their name or id.
Examples:
let number1 = form.elements.number1; let number1 = form.elements["number1"]
alert(number1[0].value); alert(number1[0].value);
let number1 = form.number1
alert(number1[0].value);
JavaScript
Forms
Accessing form & its elements in JavaScript
Accessing Elements of Form
Examples:
let number1 = document.getElementById("num1")
alert(number1.value);
Forms
Using ‘Properties’ of form elements in JavaScript
S.No. Property Description Example
let name =
1 value Gets or sets the current value of an input field.
document.getElementById("username").value;
Indicates whether a checkbox or radio button is let isChecked =
2 checked
selected. document.getElementById("agree").checked;
3 disabled Specifies if the element is disabled or not. document.getElementById("submit").disabled = true;
document.getElementById("username").readOnly =
4 readOnly Specifies whether the user can edit the input field.
true;
Retrieves the type of input element (e.g., text, let inputType =
5 type
password, checkbox). document.getElementById("password").type;
let fieldName =
6 name Returns or sets the name attribute of the form element.
document.getElementById("email").name;
document.getElementById("username").placeholder =
7 placeholder Displays a hint or placeholder text in the input field.
"Enter your name";
For dropdowns, retrieves the index of the selected let index =
8 selectedIndex
option. document.getElementById("dropdown").selectedIndex;
JavaScript
Forms
Form Events in JavaScript
Form events in JavaScript are triggers that occur when users interact with form elements.
The events allow developers to handle user actions dynamically, such as submitting a form, changing
the value of an input field, or clicking a button.
The event handlers can be used to execute specific code when an event occurs, such as validating input,
manipulating DOM elements
JavaScript provides various event handlers to respond to these events, enabling real-time validation,
feedback, and interactive behavior without needing to refresh the page.
JavaScript provides event handlers that can be attached to form elements using attributes like onsubmit,
onchange, onclick, and more.
By using these events, developers can enhance the user experience and control form interactions
effectively.
JavaScript
Forms
Form Events in JavaScript
S.No. Event Handler Description Example
2 onchange Fired when the value of an element changes. <input type="text" onchange="alert('Changed!')">
<input type="text"
3 onfocus Fired when an element gains focus.
onfocus="this.style.backgroundColor='yellow'">
<input type="text"
4 onblur Fired when an element loses focus.
onblur="this.style.backgroundColor='white'">
<button onclick="alert('Button Clicked!')">Click
5 onclick Triggered when the user clicks on an element.
Me</button>
<input type="text"
6 oninput Fired when the user types in an input field. oninput="document.getElementById('demo').innerHTML =
this.value;">
<form onreset="alert('Form reset!')"><input
7 onreset Fired when the form is reset.
type="reset"></form>
<textarea onselect="alert('Text Selected')">Select some
8 onselect Triggered when the user selects text in an input field.
text</textarea>
9 onkeypress Fired when a key is pressed down in an input field. <input type="text" onkeypress="alert('Key Pressed!')">
JavaScript
Forms
Form validation using JavaScript
Form validation is a process of ensuring that the data entered by a user into a form meets
the required criteria before it is submitted.
Forms
Form validation using JavaScript
Types of Form Validation with JavaScript
Required Field Validation: Ensures critical fields are not left blank.
Format Validation: Validates inputs like email, phone numbers, and URLs that they
follow specified format
Range Validation: Confirms numeric values or dates fall within an acceptable range.
Cross-Field Validation: Compares multiple fields (e.g., password and confirm password).
Custom Validation: Applies specific, custom rules defined by the application.
JavaScript
Forms
Form validation using JavaScript
Example:
function validateForm() {
let name = document.getElementById("name").value;
if (name === "") {
alert("Name cannot be empty.");
return false;
}
Forms
Form validation using JavaScript
Design a HTML form with name, address, pincode and password. Outline a JavaScript code that can
validate on following constraints:
a. No fields must be left blank
b. Pincode must be numeric and contain 6 digits
c. Password field
(i) At least contains 1 Capital letter.
(ii) Minimum length 8 characters.
Forms
Form validation using JavaScript
// c. Validate Password Length // c. Validate Password to Ensure It Contains at Least One Capital
if (password.length < 8) { Letter
alert("Password must be at least 8 characters long."); let hasUppercase = false;
document.getElementById("password").focus(); for (let i = 0; i < password.length; i++) {
return false; if (password[i] >= 'A' && password[i] <= 'Z') {
} hasUppercase = true;
break;
}
}
if (!hasUppercase) {
alert("Password must contain at least one uppercase letter.");
document.getElementById("password").focus();
return false;
}
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<head>
<title>Forms in JavaScript</title>
<script>
function doSum() {
let numbers =
document.forms[0].elements.number;
let val1 = numbers[0].value;
let result =
document.getElementById("result")
result.value = sum;
}
}
</script>
</head>
<body>
<form name="numOperations">
<label for="num1">Number1: </label>
<input type="text" id="num1"
name="number" value="20"><br>
<label for="num2">Number2: </label>
<input type="text" id="num2"
name="number"><br>
<label for="num3">Number3: </label>
<input type="text" id="num3"
name="number"><br>
<!-- <script>
// let form=document.forms[0]
let form=document.forms.numOperations;
// let numberElements =
form.elements.number
// let numberElements =
form.elements["number"]
//let numberElements = form.number;
//let numberElement1 =
document.getElementById("num1")
//let numberElements =
document.getElementsByName("number")
//let numberElement1 =
document.querySelector("#num1")
let numberElements =
document.querySelectorAll("#num1")
//alert(numberElement1.value)
// alert(numberElements[0].value)
</script> -->
</body>
</html>
UNIT-3 Lecture-10
Today’s Target
JavaScript
Objects
Working with Objects
Object Methods
'this' Keyword
Creating Objects with Constructors
Iterating Through Object
Useful Built-In Object Methods
AKTU PYQs
JavaScript
Objects
Objects are collections of key-value pairs in JavaScript.
They are used to represent real-world entities (e.g., a student, projector, or fan).
They are used to store multiple related pieces of data in one place.
They are used to organize and group data.
Characteristics of Objects:
Objects have properties. Keys in the key-value pairs are called properties.
Values can be any data type (numbers, strings, arrays, functions, or even other
objects).
Objects are mutable — you can add, change, or remove properties.
JavaScript
Objects
Syntax
let objectName = {
key1: value1,
key2: value2,
key3: value3
};
Example
let person = {
name: “Anubhav",
age: 18,
isStudent: true
};
JavaScript
Objects
Working with Objects
Accessing Object Properties:
Dot Notation: Used to access properties directly by their name.
Example: console.log(person.name);
Square Bracket Notation: Used to access properties using name and also
dynamically using variables or expressions.
Example: console.log(person["age"]);
Modifying Properties:
A new property can be added to an object or an existing property can be updated.
Example: person.isStudent = false; // Update
person.city = "New York"; // Add
Deleting Properties:
A property that is no longer required can be deleted.
Example: delete person.age;
JavaScript
Objects
Object Methods
A method is a function defined inside an object.
In JavaScript, functions are treated as values, means that they can be assigned to object
properties just like other built-in type values.
Example:
let user = {
name: "John",
greet: function() {
console.log("Hello");
}
};
JavaScript
Objects
'this' Keyword
let user = {
name: "Anubhav",
greet: function() {
console.log("Hello, " + this.name);
}
};
Objects
Creating Objects with Constructors
A special function used to create multiple objects with the same structure.
The regular {...} syntax allows us to create one object. But often we need to create many
similar objects, like multiple persons, books and so on. That can be done using
constructor functions and the "new" operator.
Example:
function Person(name, age) { When a constructor function is executed
with new, it does the following steps:
this.name = name;
this.age = age; 1. It creates empty object is created and
} assigned to this.
2.The function body executes. Usually it
let person1 = new Person(“Samar", 25); modifies this, adds new properties to it.
let person2 = new Person(“Digvijay", 30); 3.It returns the value of this.
console.log(person1.name); // Samar
JavaScript
Objects
Iterating Through Object
For...in loop is used to iterate over all keys in an object.
Example:
let book = {
title: "JavaScript Basics",
author: "Alice",
year: 2021
};
Objects
Useful Built-In Object Methods
Object.keys()
Returns an array of keys in the object.
Example:
let car = { brand: "Tesla", model: "X" };
console.log(Object.keys(car)); // ["brand", "model"]
Object.values()
Returns an array of values in the object.
Example:
console.log(Object.values(car)); // ["Tesla", "X"]
Object.entries()
Returns an array of [key, value] pairs.
Example:
console.log(Object.entries(car));
// [["brand", "Tesla"], ["model", "X"]]
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<head>
<title>Objects in JavaScript</title>
<script>
let topic = {
name: "JavaScript",
course: "Web Technology",
unit: 3
};
console.log(topic.course)
console.log(topic["name"])
console.log(topic[propNameFirst+propNameS
econd])
topic.branch = "CSE"
console.log(topic)
topic.course ="WT"
console.log(topic)
delete topic.branch
console.log(topic)
topic.printTopic = function() {
console.log("I am here to print the
"+this.name+" details.");
}
console.log(topic)
topic.printTopic();
console.log(topic1)
console.log(topic2)
console.log(topic3)
console.log(Object.keys(topic2))
console.log(Object.values(topic2))
console.log(Object.entries(topic2))
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-11
Today’s Target
JavaScript
Objects
String Object
Math Object
Date Object
AKTU PYQs
JavaScript
‘String’ Objects
The String Object allows manipulation of text data.
Strings are sequences of characters enclosed in quotes (single, double), or backticks (', ", or `).
String literals are automatically treated as String objects when methods are invoked.
Strings are immutable.
Note: Use string literals ("text") for efficiency unless object behavior is specifically
required.
JavaScript
‘String’ Objects
Common Property
Property Description Example
length Returns the number of characters in a string. "Hello".length → 5
Common Methods
Method Description Example
charAt(index) Returns the character at the specified index. "Hello".charAt(1) → e
toUpperCase() Converts the string to uppercase. "hello".toUpperCase() → HELLO
toLowerCase() Converts the string to lowercase. "HELLO".toLowerCase() → hello
substring(start,
Extracts a portion of the string. "Hello".substring(1, 4) → ell
end)
"Hello".concat(" World") → Hello
concat() Combines strings.
World
trim() Removes whitespace from both ends of a string. " Hello ".trim() → Hello
includes() Checks if a string contains a specified value. "Hello".includes("ll") → true
JavaScript
‘Math’ Object
The Math Object provides mathematical constants and functions.
It does not have a constructor; you cannot create instances of Math.
All methods and properties are accessed directly from Math (e.g., Math.sqrt(16)).
Common Properties
Property Description Example
Math.PI The value of π (pi). Math.PI → 3.14159
Math.E The base of natural logarithms (Euler’s number). Math.E → 2.71828
Math.SQRT2 The square root of 2. Math.SQRT2 → 1.414
Math.SQRT1_2 The square root of 1/2. Math.SQRT1_2 → 0.707
Math.LN2 The natural logarithm of 2. Math.LN2 → 0.693
Math.LN10 The natural logarithm of 10. Math.LN10 → 2.302
Math.LOG2E The base-2 logarithm of Euler’s number. Math.LOG2E → 1.442
Math.LOG10E The base-10 logarithm of Euler’s number. Math.LOG10E → 0.434
JavaScript
‘Math’ Object
Common Methods
‘Date’ Objects
The Date object in JavaScript is used to work with dates and times.
It provides methods to manipulate date and time values.
Date object internally represents time as the number of milliseconds since January 1, 1970 (UTC).
Constructors
Method Description Example
new Date() Current date and time. new Date()
new Date(dateString) Parses a date string to create a Date object. new Date("2024-11-17")
Constructs with individual components.
year: Full year (e.g., 2024).monthIndex: Month index (0 for
new Date(year, month, ...) January, 11 for December). new Date(2024, 10, 17, 14, 30)
day: Day of the month (default: 1).
hours, minutes, seconds, milliseconds: Optional; default to 0.
Date.now() Returns milliseconds since epoch. Date.now()
Date.parse("2024-11-
Date.parse(dateString) Parses a date string and returns milliseconds since epoch.
17T14:30:00")
new Date(milliseconds) Constructs a date from milliseconds since epoch. new Date(1732200000000)
JavaScript
‘Date’ Objects –
Common Methods
Method Description Example
‘Date’ Objects
Common Methods
Method Description Example
getMinutes() Returns the minutes (0-59). now.getMinutes() → 45
setMinutes() Sets the minutes (0-59). now.setMinutes(30) → Updates to 30
getSeconds() Returns the seconds (0-59). now.getSeconds() → 30
setSeconds() Sets the seconds (0-59). now.setSeconds(15) → Updates to 15
getMilliseconds() Returns the milliseconds (0-999). now.getMilliseconds() → 500
setMilliseconds() Sets the milliseconds (0-999). now.setMilliseconds(250) → Updates to 250
getTime() Returns the milliseconds since epoch. now.getTime() → 1732190730000
now.setTime(1732200000000) → Updates to
setTime() Sets the time in milliseconds since epoch.
specified epoch time
AKTU PYQs
Web Technology (AKTU 2022 – 23)
Write a program in JavaScript to display digital clock showing HH:MM:SS.
<script>
function updateClock() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
</script>
AKTU PYQs
Web Technology (AKTU 2021 – 22)
Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
<script>
function displayDateAndTime() {
var now = new Date();
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"];
<!DOCTYPE html>
<html>
<head>
<title>String Object in JavaScript</title>
<script>
let str = new String("UttarPradesh")
document.write(str.length)
document.write("<br>")
document.write(str.charAt(3))
document.write("<br>")
document.write(str.toLocaleLowerCase())
document.write("<br>")
document.write(str.toUpperCase())
document.write("<br>")
document.write(str.substring(3,7))
document.write("<br>")
document.write(str.includes("arPrrr"))
let str2="lucknow"
document.write("<br>")
document.write(typeof str)
document.write("<br>")
document.write(typeof str2)
document.write("<br>")
document.write(str2.length)
document.write("<br>")
document.write(" Delhi ".length)
document.write("<br>")
document.write(" Delhi ".trim().lengt
h)
document.write("<br>")
document.write("Uttar".concat("
Pradesh"))
</script>
</head>
<body>
</body>
</html>
MathObjectDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Math Object in JavaScript</title>
<script>
console.log(Math.PI)
console.log(Math.E)
console.log(Math.SQRT2)
console.log(Math.SQRT1_2)
console.log(Math.LN2)
console.log(Math.LN10)
console.log(Math.LOG2E)
console.log(Math.LOG10E)
console.log(Math.abs(-5))
console.log(Math.round(4.3))
console.log(Math.round(4.7))
console.log(Math.ceil(4.7))
console.log(Math.floor(4.7))
console.log(Math.pow(3,2))
console.log(Math.sqrt(9))
console.log(Math.random())
</script>
</head>
<body>
</body>
</html>
DateObjectDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Date Object in JavaScript</title>
<script>
let dateObj = new Date()
document.write(dateObj)
document.write("<br>")
document.write(dateObj.getDay())
document.write("<br>")
document.write(dateObj.getMonth())
document.write("<br>")
document.write(dateObj.getDate())
document.write("<br>")
document.write(dateObj.getFullYear())
document.write("<br>")
document.write(dateObj.getHours())
document.write("<br>")
document.write(dateObj.getMinutes())
document.write("<br>")
document.write(dateObj.getSeconds())
document.write("<br>")
document.write(dateObj.getMilliseconds())
document.write("<br>")
dateObj.setHours(19)
document.write(dateObj)
document.write("<br>")
dateObj.setMonth(2)
document.write(dateObj)
document.write("<br>")
dateObj.setHours(19)
document.write(Date.now())
let newDate = new Date(1732021400891)
document.write("<br>"+newDate)
</body>
</html>
Clock.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Digital Clock</title>
<style>
.clock {
font-size: 48px;
font-family: 'Arial', sans-serif;
color: #333;
text-align: center;
margin-top: 20%;
}
</style>
</head>
<body>
<div class="clock" id="clock">00:00:00</div>
<script>
function updateClock() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
Clock2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>Current Day and Time</title>
<style>
.time-display {
font-size: 24px;
font-family: 'Arial', sans-serif;
color: #333;
text-align: center;
margin-top: 20%;
}
</style>
</head>
<body>
<div class="time-display"
id="timeDisplay"></div>
<script>
function displayDateAndTime() {
var now = new Date();
var dayNames = ["Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"];
ObjectDemonstration.html
<!DOCTYPE html>
<html>
<head>
<title>Object</title>
<script>
let obj = new Object()
obj.name="Amol"
obj.profession="Teacher"
obj.toString = function(){
return obj.name+":"+obj.profession
};
document.write(obj)
document.write("<br>")
document.write(Object.keys(obj))
document.write("<br>")
document.write(Object.values(obj))
document.write("<br>")
document.write(Object.entries(obj))
</script>
</head>
<body>
</body>
</html>
UNIT-3 Lecture-12
Today’s Target
JavaScript
Introduction to AJAX
Features
Working
‘XMLHttpRequest’ Object
Methods
Properties
Example
AKTU PYQs
JavaScript
AJAX
AJAX stands for Asynchronous JavaScript and XML. It allows web pages to update without
reloading the entire page.
Key Features:
Asynchronous Communication:
Fetch data in the background while users interact with the page.
Partial Page Updates:
Only the necessary part of the web page is updated.
Reduces Server Load:
Sends and receives only required data, minimizing bandwidth usage.
JavaScript
AJAX
Working of AJAX
1. User Action:
Triggers an event (e.g., clicking a button).
2. AJAX Request:
JavaScript sends a request to the server.
3. Server Response:
Server processes the request and sends back data.
4. Update Page:
JavaScript dynamically updates the web page with the received data.
JavaScript
AJAX
‘XMLHttpRequest’ Object
The XMLHttpRequest object is used in JavaScript to send and receive data from a web server
asynchronously, allowing web pages to update dynamically without reloading the entire page.
It plays a key role in implementing AJAX (Asynchronous JavaScript and XML) functionality.
AJAX
‘XMLHttpRequest’ Object Methods
S.
Method Description Example
No.
Initializes a request with the specified HTTP xhr.open('GET',
1 open(method, url, async)
method, URL, and asynchronous flag. 'https://example.com/api', true);
xhr.send(); // For GET
Sends the request to the server. Optionally,
2 send(data) xhr.send(JSON.stringify({ name: 'John'
data can be included in POST requests.
})); // For POST
xhr.setRequestHeader('Content-Type',
3 setRequestHeader(header, value) Sets a custom HTTP header for the request.
'application/json');
Retrieves the value of a specific HTTP console.log(xhr.getResponseHeader('Co
4 getResponseHeader(header)
response header. ntent-Type'));
console.log(xhr.getAllResponseHeaders(
5 getAllResponseHeaders() Returns all the response headers as a string.
));
6 abort() Cancels the ongoing HTTP request. xhr.abort();
JavaScript
AJAX
‘XMLHttpRequest’ Object Properties
S. No. Property Description
1 onreadystatechange Defines a function to be called when the readyState property changes
Holds the status of the XMLHttpRequest.
0: Request not initialized
readyState 1: Server connection established
2
2: Request received
3: Processing request
4: Request finished and response is ready
AJAX
Example:
<h2>Getting Data</h2>
<p>Please click on the button to fetch data</p>
<button type="button" onclick="displayDoc()">Click Me</button>
<div id="sample">
</div>
</body>
</html>
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Math and Date objects in JavaScript. Write a program in JavaScript to display digital clock showing
HH:MM:SS.
Web Technology (AKTU 2021 – 22)
1. Create Object in JavaScript.
2. Explain the working of AJAX along with its applications. Mention a suitable example.
3. Design a JavaScript program to display the current day and time in the following format.
Today is : Monday.
Current time is : 11 AM : 50 : 58
Web Technology (AKTU 2020 – 21)
1. Explain JavaScript. Describe various objects in JavaScript.
2. Explain Function in JavaScript with suitable example.
Web Technology (AKTU 2019 – 20)
1. Discuss AJAX. Explain the application of AJAX with the help of suitable examples.
2. Compare Java and JavaScript. Explain and demonstrate 5 different types of objects in JavaScript with example.
Web Technology (AKTU 2018 – 19)
1. Compare Java and JavaScript. Write a JavaScript program to define a user defined function for sorting the values
in an array.
2. Create an html page named as “String_Math.html” and within the script tag define some string variables and use
different string function to demonstrate the use of the predefined functions. Do the same for the Math function.
AKTU PYQs
Web Designing (AKTU 2023 – 24)
1. Discuss the data types in JavaScript.
2. Explain the four types of loops in JavaScript.
3. Define JavaScript operators. What the different types of operators in JavaScript? Explain.
4. What are the three kinds of popup boxes in JavaScript? Explain.
5. What is array? Define its properties and methods.
<!DOCTYPE html>
<html>
<body>
<script>
function displayDoc() {
// Creating XMLHttpRequest object
var myObj = new XMLHttpRequest();
// Creating a callback function
myObj.onreadystatechange = function() {
if (this.readyState == 4 && this.status
== 200) {
//document.getElementById("sample").i
nnerHTML = this.responseText;
const data =
JSON.parse(this.responseText);
let outputHTML = "<ol>";
data.forEach(person => {
outputHTML +=
`<li>${person.name}, ${person.age} years old,
from ${person.city}</li>`;
});
outputHTML += "</ol>";
document.getElementById("sample").inn
erHTML = outputHTML;
}else{
console.log("Error Found")
}
};
// Open the given file
myObj.open("GET",
"http://localhost:8000/data.json", true);
</div>
</body>
</html>
UNIT-3 Lecture-13
Today’s Target
Networking
Internet Addressing
InetAddress
Factory Methods
Instance Methods
URL
URLConnection
AKTU PYQs
Web Technology
UNIT – III:
Scripting:
JavaScript: Introduction, documents, forms, statements, functions, objects, Introduction
to AJAX.
Networking:
Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP Client
Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram.
Networking
Internet Addressing
An Internet address is a number that uniquely identifies each computer/ device on the
Internet.
Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit
values. This address type was specified by IPv4 (Internet Protocol, version 4).
A new addressing scheme, called IPv6 uses a 128-bit value to represent an address,
organized into eight 16-bit chunks.
IPv6 supports a much larger address space than does IPv4.
When using Java, we need not to worry about whether IPv4 or IPv6 addresses are used
because Java handles the underlying details for programmers.
The name of an Internet address, called its domain name, describes a machine’s location
as a name.
An Internet domain name is mapped to an IP address by the Domain Name System
(DNS).
This enables users to work with domain names, provided Internet actually operates on IP
addresses.
Networking
InetAddress
In Java, the InetAddress class (contained in java.net package) represents Internet Address
objects. It encapsulates both the numerical IP address and the domain name for that
address.
You interact with this class by using the name of an IP host, which is more convenient
and understandable than its IP address. The InetAddress class hides the number inside.
InetAddress can handle both IPv4 and IPv6 addresses.
Factory Methods
Factory Methods are used to create an InetAddress object as the InetAddress class has no
visible constructors.
Factory methods are a convention whereby static methods within a class are used to
create and return instances of that class. This approach is preferred over using overloaded
constructors with multiple parameter options, as distinct method names can make the
purpose and behavior of each method more understandable.
Networking
InetAddress
Factory Methods
Three commonly used InetAddress factory methods are shown here:
Note: If these methods are unable to resolve the host name, they throw an UnknownHostException.
Networking
InetAddress
Factory Methods
Example:
import java.net.InetAddress;
import java.net.UnknownHostException;
address = InetAddress.getByName("courses.gatewayclasses.in");
System.out.println(address);
InetAddress
Instance Methods
The InetAddress class has several other methods, which can be used on the objects returned
by the factory methods:
boolean equals(Object other) Returns true if this object has the same Internet address as other.
byte[ ] getAddress( ) Returns a byte array that represents the object’s IP address in
network byte order.
String getHostAddress( ) Returns a string that represents the host address associated with
the InetAddress object.
String getHostName( ) Returns a string that represents the host name associated with the
InetAddress object.
String toString( ) Returns a string that lists the host name and the IP address for
convenience.
Networking
InetAddress
Instance Methods
Example:
import java.net.*;
public class InetAddressInstanceMethodsDemo {
public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
InetAddress address = InetAddress.getByName("courses.gatewayclasses.in");
byte[] addressBytes = address.getAddress();
for(byte addressByte: addressBytes)
System.out.println(addressByte);
System.out.println(address.getHostAddress());
System.out.println(address.getHostName());
boolean isEqual = address.equals(localHost);
System.out.println(isEqual);
System.out.println(localHost.toString());
System.out.println(address);
}
}
Networking
Uniform Resource Locator (URL)
The URL is a reference (an address) to a resource on the Internet. Every browser
uses them to identify information on the Web.
A URL has two main components
1. Protocol Identifier
2. Resource Name
Example : http://java.sun.com/
http : Protocol Identifier
java.sun.com/ : Resource Name
The Resource Name may contain
Host Name : The name of the machine
File Name : The pathname of the file on the machine
Port Number : The port number to which to connect (Optional)
Reference : A reference to a named anchor within a resource (Optional)
Networking
String getProtocol(): Returns the protocol of the URL (e.g., http, https, ftp).
String getHost(): Returns the hostname or IP address of the URL.
int getPort(): Returns the port number specified in the URL, or -1 if none is
explicitly mentioned.
String getFile(): Returns the file name or path specified in the URL, including the
query string if present.
String getRef(): Returns the reference (anchor) part of the URL, typically after the
# symbol.
Networking
URL
Instance Methods
Parsing a URL - Example:
import java.net.*;
public class URLDemo {
public static void main(String[]args) throws MalformedURLException {
URL url = new
URL("http://java.sun.com:80/docs/books/tutorial/intro.html#DOWNLOADING");
System.out.println("Protocol = "+url.getProtocol());
System.out.println("Host = "+url.getHost());
System.out.println("Port = "+url.getPort());
System.out.println("FileName = "+url.getFile());
System.out.println("Reference= "+url.getRef());
}
}
Networking
}
AKTU PYQs
Web Technology (AKTU 2022 – 23)
1. Discuss about Java Socket Programming. Write a program in Java to create client and server using Socket,
ServerSocket class.
import java.net.*;
try {
InetAddress address1 =
InetAddress.getLocalHost();
InetAddress address2 =
InetAddress.getByName("www.google.co.in");
InetAddress[] address3 =
InetAddress.getAllByName("www.google.co.in");
System.out.println(address1.getHostAddress());
System.out.println(address1.equals(address2));
System.out.println(address1);
System.out.println(address2.toString());
System.out.println(address2.getHostName());
System.out.println(address);
System.out.println(uHostException);
URLDemo.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
URISyntaxException,IOException {
try{
URL("https://www.example.com:8080/wt/myfolder/index.html#f
irst");
URL("http","www.google.co.in",8635,"/one/index.html");
HttpURLConnection urlConn =
(HttpURLConnection)url2.openConnection();
System.out.println(url2.getProtocol());
System.out.println(url2.getHost());
System.out.println(url2.getFile());
System.out.println(url2.getPort());
System.out.println(url2.getRef());
System.out.println(urlConn.getRequestMethod())
System.out.println(urlConn.getResponseCode());
System.out.println(urlConn.getResponseMessage(
));
System.out.println(urlConn.getContentLength())
System.out.println(urlConn.getContentType());
System.out.println(urlConn.getHeaderField(0));
System.out.println(urlConn.getHeaderFieldKey(0
));
int i=0;
System.err.print((char)i);
catch(MalformedURLException mUrlException){
System.out.println(mUrlException);
}
UNIT-3 Lecture-14
Today’s Target
Networking
TCP/IP Client Sockets
TCP/IP Server Sockets
Datagram
AKTU PYQs
Web Technology
UNIT – III:
Scripting:
JavaScript: Introduction, documents, forms, statements, functions, objects, Introduction
to AJAX.
Networking:
Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP Client
Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram.
Networking
Socket
“A socket is an endpoint for communication between two machines over a network.”
A socket is essentially the combination of:
IP Address: Identifies the specific device on the network.
Port Number: Identifies a specific process or service running on that device.
Together, these ensure that data is delivered to the correct application on the correct
machine. This combination is often referred to as a socket address.
Example: 192.168.1.10:8080
This socket refers to the application listening on port 8080 of the machine
with IP address 192.168.1.10.
Networking
Socket
Types of Sockets:
Stream Sockets (TCP Sockets)
Use TCP (Transmission Control Protocol) for reliable, connection-oriented
communication.
Example: In Java, the Socket class represents a client-side TCP Socket, while the
ServerSocket class represents a server socket.
Socket Programming
It involves creating endpoints, called sockets, on both client and server sides to establish a
connection for exchanging data.
In Java, Socket Programming enables the implementation of both TCP (reliable, connection-
oriented) and UDP (fast, connectionless) communication using classes like Socket,
ServerSocket, and DatagramSocket.
Networking
Client
Client socket initiates a TCP connection to the server by creating a socket object.
It specifies the address of the server process, namely, the IP address of the server
and the port number of the process.
Networking
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
Networking
Datagrams
“Datagrams are bundles of information passed between machines.”
Once the datagram has been released to its intended target, there is no assurance that it
will arrive or even that someone will be there to receive it.
Likewise, when the datagram is received, there is no assurance that it hasn’t been
damaged in transit or that whoever sent it is still there to receive a response.
Java implements datagrams on top of the UDP protocol by using two classes:
User Datagram Protocol (UDP) can be used directly to support fast, connectionless,
unreliable transport of packets.
Connectionless and unreliable service.
There is no initial handshaking phase.
The transmitted data may be received out of order, or lost
write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port umber close
clientSocket
Networking
import java.io.*;
import java.net.*;
class TCPClient {
Exception {
String sentence;
String modifiedSentence;
InputStreamReader(System.in));
6789);
DataOutputStream(clientSocket.getOutputStream());
BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
modifiedSentence);
clientSocket.close();
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket(6789);
while (true) {
Socket connectionSocket =
welcomeSocket.accept();
BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
clientSentence);
capitalizedSentence =
clientSentence.toUpperCase() + '\n';
capitalizedSentence);
outToClient.writeBytes(capitalizedSentence);
}
UDPClient.java
import java.io.*;
import java.net.*;
class UDPClient
Exception
InputStreamReader(System.in));
DatagramSocket();
InetAddress IPAddress =
InetAddress.getByName("localhost");
sendData = sentence.getBytes();
DatagramPacket sendPacket = new
DatagramPacket(sendData, sendData.length,
IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String(receivePacket.getData());
System.out.println("FROM SERVER:" +
modifiedSentence.trim());
clientSocket.close();
UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws
Exception
DatagramSocket(9876);
while(!(endString.substring(0,3).equalsIgnoreCase(
"Bye")))
DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String(receivePacket.getData());
System.out.println("FROM CLIENT:
"+sentence.trim());
InetAddress IPAddress =
receivePacket.getAddress();
sentence.toUpperCase();
endString=sentence;
sendData = capitalizedSentence.getBytes();
DatagramPacket(sendData,
sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
serverSocket.close();