0% found this document useful (0 votes)
19 views

WT unit2

JavaScript is a versatile programming language primarily used for web development, enabling dynamic manipulation of HTML and CSS. It supports both client-side and server-side scripting, allowing for interactive web applications and dynamic content generation. JavaScript utilizes objects, variables, and various operators to perform operations and manage data effectively.

Uploaded by

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

WT unit2

JavaScript is a versatile programming language primarily used for web development, enabling dynamic manipulation of HTML and CSS. It supports both client-side and server-side scripting, allowing for interactive web applications and dynamic content generation. JavaScript utilizes objects, variables, and various operators to perform operations and manage data effectively.

Uploaded by

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

JavaScript

JavaScript is the programming language of the web.

It can update and change both HTML and CSS.

It can calculate, manipulate and validate data.

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

JavaScript Can Change HTML Content.

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »
JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:

The Light Bulb

Turn on the light Turn off the light


JavaScript Can Change HTML Styles (CSS).

Changing the style of an HTML element, is a variant of changing an HTML


attribute:

Example
document.getElementById("demo").style.fontSize = "35px";
JavaScript Can Hide HTML Elements.

Hiding HTML elements can be done by changing the display style:

Example
document.getElementById("demo").style.display = "none";
JavaScript Can Show HTML Elements.

Showing hidden HTML elements can also be done by changing the display style:

Example
document.getElementById("demo").style.display = "block";
1. Client-side scripting :
Web browsers execute client-side scripting. It is used when browsers have all code.
Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without going to
the user. It cannot be basically used to connect to databases on a web server. These
scripts cannot access the file system that resides in the web browser. Pages are
altered on basis of the user’s choice. It can also be used to create “cookies” that
store data on the user’s computer.
2. Server-side scripting :
Web servers are used to execute server-side scripting. They are basically used to
create dynamic pages. It can also access the file system residing at the webserver.
A server-side environment that runs on a scripting language is a web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is used to
require to download plugins. In this load times are generally faster than client-side
scripting. When you need to store and retrieve information a database will be used
to contain data. It can use huge resources of the server. It reduces client-side
computation overhead. The server sends pages to the request of the user/client.
Difference between client-side scripting and server-side scripting :
Client-side scripting Server-side scripting

Source code is not visible to the user


because its output
Source code is visible to the user.
of server-sideside is an HTML page.

Its primary function is to manipulate and


Its main function is to provide the
provide access to the respective database as
requested output to the end user.
per the request.

In this any server-side technology can be


It usually depends on the browser used and it does not
and its version. depend on the client.

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked


The primary advantage is its ability to
with this like faster.
highly customize, response
response times, a more interactive
requirements, access rights based on user.
application.

It does not provide security for


It provides more security for data.
data.
Client-side scripting Server-side scripting

It is a technique used in web It is a technique that uses scripts on the


development in which scripts run webserver to produce a response that is
on the client’s browser. customized for each client’s request.

HTML, CSS, and javascript are


PHP, Python, Java, Ruby are used.
used.

No need of interaction with the


It is all about interacting with the servers.
server.

It reduces load on processing unit


It surge the processing load on the server.
of the server.

JavaScript Objects
Real Life Objects

In real life, objects are things like: houses, cars, people, animals, or any other
subjects.

Here is a car object example:

Car Object Properties

car.name = Fiat

car.model = 500

car.weight = 850kg
car.color = white

Object Properties

A real life car has properties like weight and color:

car.name = Fiat, car.model = 500, car.weight = 850kg, car.color = white.

Car objects have the same properties, but the values differ from car to car.

Object Methods

A real life car has methods like start and stop:

car.start(), car.drive(), car.brake(), car.stop().

Car objects have the same methods, but the methods are performed at different
times.

JavaScript Variables

JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

Example
let car = "Fiat";

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to an object named car:

Example
const car = {type:"Fiat", model:"500", color:"white"};

JavaScript Object Definition


How to Define a JavaScript Object
 Using an Object Literal
 Using the new Keyword
 Using an Object Constructor

JavaScript Object Literal

An object literal is a list of name:value pairs inside curly braces {}.

{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

Creating a JavaScript Object

These examples create a JavaScript object with 4 properties:

Examples
// Create an Object
const person = {firstName:"harjas", lastName:"singh", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object initializer can span multiple
lines:

// Create an Object
const person = {
firstName: "harjas",
lastName: "singh",
age: 50,
eyeColor: "blue"
};

This example creates an empty JavaScript object, and then adds 4 properties:

// Create an Object
const person = {};

// Add Properties
person.firstName = "harjas";
person.lastName = "singh";
person.age = 50;
person.eyeColor = "blue";
Using the new Keyword

This example create a new JavaScript object using new Object(), and then adds 4
properties:

Example
// Create an Object
const person = new Object();

// Add Properties
person.firstName = "harjas";
person.lastName = "singh";
person.age = 50;
person.eyeColor = "blue";

Object Properties

The named values, in JavaScript objects, are called properties.

Property Value

firstName harjas

lastName singh

age 50

eyeColor blue

Accessing Object Properties


You can access object properties in two ways:

objectName.propertyName

objectName["propertyName"]

Examples
person.lastName;

person["lastName"];

JavaScript Object Methods

Methods are actions that can be performed on objects.

Methods are function definitions stored as property values.

Property Property Value

firstName harjas

lastName singh

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}


Example
const person = {
firstName: "harjas",
lastName : "singh",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

In the example above, this refers to the person object:

this.firstName means the firstName property of person.

this.lastName means the lastName property of person.

In JavaScript, Objects are King.


If you Understand Objects, you Understand JavaScript.

Objects are containers for Properties and Methods.

Properties are named Values.

Methods are Functions stored as Properties.

Properties can be primitive values, functions, or even other objects.

In JavaScript, almost "everything" is an object.

 Objects are objects


 Maths are objects
 Functions are objects
 Dates are objects
 Arrays are objects
 Maps are objects
 Sets are objects
All JavaScript values, except primitives, are objects.

JavaScript Primitives

A primitive value is a value that has no properties or methods.

A primitive data type is data that has a primitive value.

JavaScript defines 7 types of primitive data types:

 string
 number
 boolean
 null
 undefined
 symbol
 bigint

Immutable

Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.

Value Type Comment

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

true boolean true is always true


false boolean false is always false

null null (object) null is always null

undefined undefined undefined is always undefined

JavaScript Objects are Mutable

Objects are mutable: They are addressed by reference, not by value.

If person is an object, the following statement will not create a copy of person:

const x = person;

The object x is not a copy of person. The object x is person.

The object x and the object person share the same memory address.

Any changes to x will also change person:

Example
//Create an Object
const person = {
firstName:"harjas",
lastName:"singh",
age:50, eyeColor:"blue"
}

// Create a copy
const x = person;
// Change Age in both
x.age = 10;

Expressions and operators

At a high level, an expression is a valid unit of code that resolves to a value. There
are two types of expressions: those that have side effects (such as assigning values)
and those that purely evaluate.

The expression x = 7 is an example of the first type. This expression uses


the = operator to assign the value seven to the variable x. The expression itself
evaluates to 7.

The expression 3 + 4 is an example of the second type. This expression uses


the + operator to add 3 and 4 together and produces a value, 7. However, if it's not
eventually part of a bigger construct (for example, a variable declaration like const
z = 3 + 4), its result will be immediately discarded — this is usually a programmer
mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined
by operators, such as = and +. In this section, we will introduce the following
operators:

 Assignment operators
 Comparison operators
 Arithmetic operators
 Bitwise operators
 Logical operators
 BigInt operators
 String operators
 Conditional (ternary) operator
 Comma operator
 Unary operators
 Relational operators

These operators join operands either formed by higher-precedence operators or one


of the basic expressions. A complete and detailed list of operators and expressions
is also available in the reference.
The precedence of operators determines the order they are applied when evaluating
an expression. For example:

JSCopy to Clipboard

const x = 1 + 2 * 3;
const y = 2 * 3 + 1;

Despite * and + coming in different orders, both expressions would result


in 7 because * has precedence over +, so the *-joined expression will always be
evaluated first. You can override operator precedence by using parentheses (which
creates a grouped expression — the basic expression). To see a complete table of
operator precedence as well as various caveats, see the Operator Precedence
Reference page.

JavaScript has both binary and unary operators, and one special ternary operator,
the conditional operator. A binary operator requires two operands, one before the
operator and one after the operator:

operand1 operator operand2

For example, 3 + 4 or x * y. This form is called an infix binary operator, because


the operator is placed between two operands. All binary operators in JavaScript are
infix.

A unary operator requires a single operand, either before or after the operator:

operator operand
operand operator

For example, x++ or ++x. The operator operand form is called a prefix unary
operator, and the operand operator form is called a postfix unary operator. ++ and -
- are the only postfix operators in JavaScript — all other operators, like !, typeof,
etc. are prefix.

Assignment operators

An assignment operator assigns a value to its left operand based on the value of its
right operand. The simple assignment operator is equal (=), which assigns the
value of its right operand to its left operand. That is, x = f() is an assignment
expression that assigns the value of f() to x.
There are also compound assignment operators that are shorthand for the
operations listed in the following table:

Name Shorthand operator Meaning

Assignment x = f() x = f()

Addition assignment x += f() x = x + f()

Subtraction assignment x -= f() x = x - f()

Multiplication assignment x *= f() x = x * f()

Division assignment x /= f() x = x / f()

Remainder assignment x %= f() x = x % f()

Exponentiation assignment x **= f() x = x ** f()

Left shift assignment x <<= f() x = x << f()

Right shift assignment x >>= f() x = x >> f()

Unsigned right shift assignment x >>>= f() x = x >>> f()

Bitwise AND assignment x &= f() x = x & f()

Bitwise XOR assignment x ^= f() x = x ^ f()

Bitwise OR assignment x |= f() x = x | f()

Logical AND assignment x &&= f() x && (x = f())

Logical OR assignment x ||= f() x || (x = f())

Nullish coalescing assignment x ??= f() x ?? (x = f())

Assigning to properties

If an expression evaluates to an object, then the left-hand side of an assignment


expression may make assignments to properties of that expression. For example:
JSCopy to Clipboard

const obj = {};

obj.x = 3;
console.log(obj.x); // Prints 3.
console.log(obj); // Prints { x: 3 }.

const key = "y";


obj[key] = 5;
console.log(obj[key]); // Prints 5.
console.log(obj); // Prints { x: 3, y: 5 }.

If an expression does not evaluate to an object, then assignments to properties of


that expression do not assign:

JSCopy to Clipboard

const val = 0;
val.x = 3;

console.log(val.x); // Prints undefined.


console.log(val); // Prints 0.

In strict mode, the code above throws, because one cannot assign properties to
primitives.

It is an error to assign values to unmodifiable properties or to properties of an


expression without properties (null or undefined).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript


expression that makes it possible to extract data from arrays or objects using a
syntax that mirrors the construction of array and object literals.

Without destructuring, it takes multiple statements to extract values from arrays


and objects:

JSCopy to Clipboard
const foo = ["one", "two", "three"];

const one = foo[0];


const two = foo[1];
const three = foo[2];

With destructuring, you can extract multiple values into distinct variables using a
single statement:

JSCopy to Clipboard

const [one, two, three] = foo;

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const, let,
or var) or as standalone statements.

JSCopy to Clipboard

// Declares a variable x and initializes it to the result of f().


// The result of the x = f() assignment expression is discarded.
let x = f();

x = g(); // Reassigns the variable x to the result of g().

However, like other expressions, assignment expressions like x = f() evaluate into
a result value. Although this result value is usually not used, it can then be used by
another expression.

Chaining assignments or nesting assignments in other expressions can result in


surprising behavior. For this reason, some JavaScript style guides discourage
chaining or nesting assignments. Nevertheless, assignment chaining and nesting
may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to


another variable. It can be logged, it can be put inside an array literal or function
call, and so on.

JSCopy to Clipboard

let x;
const y = (x = f()); // Or equivalently: const y = x = f();
console.log(y); // Logs the return value of the assignment x = f().

console.log(x = f()); // Logs the return value directly.

// An assignment expression can be nested in any place


// where expressions are generally allowed,
// such as array literals' elements or as function calls' arguments.
console.log([0, x = f(), 0]);
console.log(f(0, x = f(), 0));

The evaluation result matches the expression to the right of the = sign in the
"Meaning" column of the table above. That means that x = f() evaluates into
whatever f()'s result is, x += f() evaluates into the resulting sum x + f(), x **=
f() evaluates into the resulting power x ** f(), and so on.

In the case of logical assignments, x &&= f(), x ||= f(), and x ??= f(), the return
value is that of the logical operation without the assignment, so x && f(), x || f(),
and x ?? f(), respectively.

When chaining these expressions without parentheses or other grouping operators


like array literals, the assignment expressions are grouped right to left (they
are right-associative), but they are evaluated left to right.

Note that, for all assignment operators other than = itself, the resulting values are
always based on the operands' values before the operation.

For example, assume that the following functions f and g and the
variables x and y have been declared:

JSCopy to Clipboard

function f() {
console.log("F!");
return 2;
}
function g() {
console.log("G!");
return 3;
}
let x, y;
Consider these three examples:

JSCopy to Clipboard

y = x = f();
y = [f(), x = g()];
x[f()] = g();
Evaluation example 1

y = x = f() is equivalent to y = (x = f()), because the assignment operator = is right-


associative. However, it evaluates from left to right:

1. The assignment expression y = x = f() starts to evaluate.


i. The y on this assignment's left-hand side evaluates into a reference to the
variable named y.
ii. The assignment expression x = f() starts to evaluate.
i. The x on this assignment's left-hand side evaluates into a reference to the
variable named x.
ii. The function call f() prints "F!" to the console and then evaluates to the
number 2.
iii. That 2 result from f() is assigned to x.
iii. The assignment expression x = f() has now finished evaluating; its result is
the new value of x, which is 2.
iv. That 2 result in turn is also assigned to y.
2. The assignment expression y = x = f() has now finished evaluating; its result
is the new value of y – which happens to be 2. x and y are assigned to 2, and
the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

1. The assignment expression y = [ f(), x = g() ] starts to evaluate.


i. The y on this assignment's left-hand evaluates into a reference to the variable
named y.
ii. The inner array literal [ f(), x = g() ] starts to evaluate.
i. The function call f() prints "F!" to the console and then evaluates to the
number 2.
ii. The assignment expression x = g() starts to evaluate.
i. The x on this assignment's left-hand side evaluates into a reference to the
variable named x.
ii. The function call g() prints "G!" to the console and then evaluates to the
number 3.
iii. That 3 result from g() is assigned to x.
iii. The assignment expression x = g() has now finished evaluating; its result is
the new value of x, which is 3. That 3 result becomes the next element in the
inner array literal (after the 2 from the f()).
iii. The inner array literal [ f(), x = g() ] has now finished evaluating; its result is
an array with two values: [ 2, 3 ].
iv. That [ 2, 3 ] array is now assigned to y.
2. The assignment expression y = [ f(), x = g() ] has now finished evaluating;
its result is the new value of y – which happens to be [ 2, 3 ]. x is now
assigned to 3, y is now assigned to [ 2, 3 ], and the console has printed "F!"
then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is
already assigned to some object. For more information about objects,
read Working with Objects.)

1. The assignment expression x[f()] = g() starts to evaluate.


i. The x[f()] property access on this assignment's left-hand starts to evaluate.
i. The x in this property access evaluates into a reference to the variable
named x.
ii. Then the function call f() prints "F!" to the console and then evaluates to the
number 2.
ii. The x[f()] property access on this assignment has now finished evaluating;
its result is a variable property reference: x[2].
iii. Then the function call g() prints "G!" to the console and then evaluates to the
number 3.
iv. That 3 is now assigned to x[2]. (This step will succeed only if x is assigned
to an object.)
2. The assignment expression x[f()] = g() has now finished evaluating; its
result is the new value of x[2] – which happens to be 3. x[2] is now assigned
to 3, and the console has printed "F!" then "G!".

Avoid assignment chains


Chaining assignments or nesting assignments in other expressions can result in
surprising behavior. For this reason, chaining assignments in the same statement is
discouraged.

In particular, putting a variable chain in a const, let, or var statement often


does not work. Only the outermost/leftmost variable would get declared; other
variables within the assignment chain are not declared by
the const/let/var statement. For example:

JSCopy to Clipboard

const z = y = x = f();

This statement seemingly declares the variables x, y, and z. However, it only


actually declares the variable z. y and x are either invalid references to nonexistent
variables (in strict mode) or, worse, would implicitly create global
variables for x and y in sloppy mode.

Comparison operators

A comparison operator compares its operands and returns a logical value based on
whether the comparison is true. The operands can be numerical, string, logical,
or object values. Strings are compared based on standard lexicographical ordering,
using Unicode values. In most cases, if the two operands are not of the same type,
JavaScript attempts to convert them to an appropriate type for the comparison. This
behavior generally results in comparing the operands numerically. The sole
exceptions to type conversion within comparisons involve
the === and !== operators, which perform strict equality and inequality
comparisons. These operators do not attempt to convert the operands to compatible
types before checking equality. The following table describes the comparison
operators in terms of this sample code:

JSCopy to Clipboard

const var1 = 3;
const var2 = 4;
Comparison operators

Examples
Operator Description
returning tr
Comparison operators

Examples
Operator Description
returning tr

3 == var1

Equal (==) Returns true if the operands are equal. "3" == var1

3 == '3'

var1 != 4
Not equal (!=) Returns true if the operands are not equal.
var2 != "3"

Returns true if the operands are equal and of the same type. See
Strict equal (===) 3 === var1
also Object.is and sameness in JS.

Strict not Returns true if the operands are of the same type but not equal, var1 !== "3"
equal (!==) or are of different type. 3 !== '3'

var2 > var1


Greater than (>) Returns true if the left operand is greater than the right operand.
"12" > 2

Greater than or Returns true if the left operand is greater than or equal to the var2 >= var1
equal (>=) right operand. var1 >= 3

var1 < var2


Less than (<) Returns true if the left operand is less than the right operand.
"2" < 12

Less than or Returns true if the left operand is less than or equal to the right var1 <= var2
equal (<=) operand. var2 <= 5

Arithmetic operators

An arithmetic operator takes numerical values (either literals or variables) as their


operands and returns a single numerical value. The standard arithmetic operators
are addition (+), subtraction (-), multiplication (*), and division (/). These operators
work as they do in most other programming languages when used with floating
point numbers (in particular, note that division by zero produces Infinity). For
example:

JSCopy to Clipboard

1 / 2; // 0.5
1 / 2 === 1.0 / 2.0; // this is true

In addition to the standard arithmetic operations (+, -, *, /), JavaScript provides the
arithmetic operators listed in the following table:

Arithmetic operators

Operator Description Example

Binary operator. Returns the integer remainder of


Remainder (%) 12 % 5 returns 2.
dividing the two operands.

Unary operator. Adds one to its operand. If used as


If x is 3, then ++x sets x to
a prefix operator (++x), returns the value of its
and returns 4,
Increment (++) operand after adding one; if used as a postfix
whereas x++ returns 3 and
operator (x++), returns the value of its operand
then, sets x to 4.
before adding one.

Unary operator. Subtracts one from its operand. If x is 3, then --x sets x to 2
Decrement (--) The return value is analogous to that for the returns 2, whereas x-- retur
increment operator. and, only then, sets x to 2.

Unary Unary operator. Returns the negation of its


If x is 3, then -x returns -3.
negation (-) operand.

Unary operator. Attempts to convert the operand to +"3" returns 3.


Unary plus (+)
a number, if it is not already.
+true returns 1.
Exponentiation Calculates the base to the exponent power, that 2 ** 3 returns 8.
operator (**) is, base^exponent 10 ** -1 returns 0.1.

Bitwise operators
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather
than as decimal, hexadecimal, or octal numbers. For example, the decimal number
nine has a binary representation of 1001. Bitwise operators perform their
operations on such binary representations, but they return standard JavaScript
numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description

Returns a one in each bit position for which the corresponding bits of b
Bitwise AND a&b
operands are ones.

Returns a zero in each bit position for which the corresponding bits of b
Bitwise OR a|b
operands are zeros.

Returns a zero in each bit position for which the corresponding bits are
Bitwise XOR a ^ b same. [Returns a one in each bit position for which the corresponding b
are different.]

Bitwise NOT ~a Inverts the bits of its operand.

Shifts a in binary representation b bits to the left, shifting in zeros from


Left shift a << b
right.

Sign-propagating Shifts a in binary representation b bits to the right, discarding bits shifte
a >> b
right shift off.

Zero-fill right a >>> Shifts a in binary representation b bits to the right, discarding bits shifte
shift b off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

 The operands are converted to thirty-two-bit integers and expressed by a


series of bits (zeros and ones). Numbers with more than 32 bits get their
most significant bits discarded. For example, the following integer with
more than 32 bits will be converted to a 32-bit integer:
 Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001
 After: 1010 0000 0000 0000 0110 0000 0000 0001
 Each bit in the first operand is paired with the corresponding bit in the
second operand: first bit to first bit, second bit to second bit, and so on.
 The operator is applied to each pair of bits, and the result is constructed
bitwise.

For example, the binary representation of nine is 1001, and the binary
representation of fifteen is 1111. So, when the bitwise operators are applied to
these values, the results are as follows:

Expression Result Binary Description

15 & 9 9 1111 & 1001 = 1001

15 | 9 15 1111 | 1001 = 1111

15 ^ 9 6 1111 ^ 1001 = 0110

~15 -16 ~ 0000 0000 … 0000 1111 = 1111 1111 … 1111 0000

~9 -10 ~ 0000 0000 … 0000 1001 = 1111 1111 … 1111 0110

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values
with the most significant (left-most) bit set to 1 represent negative numbers (two's-
complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted,
and the second specifies the number of bit positions by which the first operand is to
be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result
of either type Number or BigInt: specifically, if the type of the left operand
is BigInt, they return BigInt; otherwise, they return Number.

The shift operators are listed in the following table.

Bitwise shift operators


Operator Description Example

This operator shifts the first operand the


specified number of bits to the left.
Left shift 9<<2 yields 36, because 1001 shifted 2
Excess bits shifted off to the left are
(<<) to the left becomes 100100, which is 3
discarded. Zero bits are shifted in from
the right.

This operator shifts the first operand the


9>>2 yields 2, because 1001 shifted 2 b
Sign- specified number of bits to the right.
to the right becomes 10, which is 2.
propagating Excess bits shifted off to the right are
Likewise, -9>>2 yields -3, because the
right shift (>>) discarded. Copies of the leftmost bit are
is preserved.
shifted in from the left.

This operator shifts the first operand the 19>>>2 yields 4, because 10011 shifte
specified number of bits to the right. bits to the right becomes 100, which is
Zero-fill right
Excess bits shifted off to the right are For non-negative numbers, zero-fill rig
shift (>>>)
discarded. Zero bits are shifted in from shift and sign-propagating right shift y
the left. the same result.

Logical operators

Logical operators are typically used with Boolean (logical) values; when they are,
they return a Boolean value. However, the &&, ||, and ?? operators actually return
the value of one of the specified operands, so if these operators are used with non-
Boolean values, they may return a non-Boolean value. As such, they are more
adequately called "value selection operators". The logical operators are described
in the following table.

Logical operators

Operator Usage Description

expr1 Returns expr1 if it can be converted to false; otherwise, returns expr


Logical
&& Thus, when used with Boolean values, && returns true if both opera
AND (&&)
expr2 are true; otherwise, returns false.
Logical operators

Operator Usage Description

Returns expr1 if it can be converted to true; otherwise, returns expr2


expr1 ||
Logical OR (||) Thus, when used with Boolean values, || returns true if either operan
expr2
true; if both are false, returns false.

Nullish coalescing expr1 ??


Returns expr1 if it is neither null nor undefined; otherwise, returns e
operator (??) expr2

Returns false if its single operand can be converted to true; otherwis


Logical NOT (!) !expr
returns true.

Examples of expressions that can be converted to false are those that evaluate
to null, 0, 0n, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

JSCopy to Clipboard

const a1 = true && true; // t && t returns true


const a2 = true && false; // t && f returns false
const a3 = false && true; // f && t returns false
const a4 = false && 3 === 4; // f && f returns false
const a5 = "Cat" && "Dog"; // t && t returns Dog
const a6 = false && "Cat"; // f && t returns false
const a7 = "Cat" && false; // t && f returns false

The following code shows examples of the || (logical OR) operator.

JSCopy to Clipboard

const o1 = true || true; // t || t returns true


const o2 = false || true; // f || t returns true
const o3 = true || false; // t || f returns true
const o4 = false || 3 === 4; // f || f returns false
const o5 = "Cat" || "Dog"; // t || t returns Cat
const o6 = false || "Cat"; // f || t returns Cat
const o7 = "Cat" || false; // t || f returns Cat
The following code shows examples of the ?? (nullish coalescing) operator.

JSCopy to Clipboard

const n1 = null ?? 1; // 1
const n2 = undefined ?? 2; // 2
const n3 = false ?? 3; // false
const n4 = 0 ?? 4; // 0

Note how ?? works like ||, but it only returns the second expression when the first
one is "nullish", i.e. null or undefined. ?? is a better alternative than || for setting
defaults for values that might be null or undefined, in particular when values
like '' or 0 are valid values and the default should not apply.

The following code shows examples of the ! (logical NOT) operator.

JSCopy to Clipboard

const n1 = !true; // !t returns false


const n2 = !false; // !f returns true
const n3 = !"Cat"; // !t returns false

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible
"short-circuit" evaluation using the following rules:

 falsy && anything is short-circuit evaluated to the falsy value.


 truthy || anything is short-circuit evaluated to the truthy value.
 nonNullish ?? anything is short-circuit evaluated to the non-nullish value.

The rules of logic guarantee that these evaluations are always correct. Note that
the anything part of the above expressions is not evaluated, so any side effects of
doing so do not take effect.

BigInt operators

Most operators that can be used between numbers can be used


between BigInt values as well.

JSCopy to Clipboard
// BigInt addition
const a = 1n + 2n; // 3n
// Division with BigInts round towards zero
const b = 1n / 2n; // 0n
// Bitwise operations with BigInts do not truncate either side
const c = 40000000000000000n >> 2n; // 10000000000000000n

One exception is unsigned right shift (>>>), which is not defined for BigInt values.
This is because a BigInt does not have a fixed width, so technically it does not
have a "highest bit".

JSCopy to Clipboard

const d = 8n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >>
instead

BigInts and numbers are not mutually replaceable — you cannot mix them in
calculations.

JSCopy to Clipboard

const a = 1n + 2; // TypeError: Cannot mix BigInt and other types

This is because BigInt is neither a subset nor a superset of numbers. BigInts have
higher precision than numbers when representing large integers, but cannot
represent decimals, so implicit conversion on either side might lose precision. Use
explicit conversion to signal whether you wish the operation to be a number
operation or a BigInt one.

JSCopy to Clipboard

const a = Number(1n) + 2; // 3
const b = 1n + BigInt(2); // 3n

You can compare BigInts with numbers.

JSCopy to Clipboard

const a = 1n > 2; // false


const b = 3 > 2n; // true

String operators
In addition to the comparison operators, which can be used on string values, the
concatenation operator (+) concatenates two string values together, returning
another string that is the union of the two operand strings.

For example,

JSCopy to Clipboard

console.log("my " + "string"); // console logs the string "my string".

The shorthand assignment operator += can also be used to concatenate strings.

For example,

JSCopy to Clipboard

let myString = "alpha";


myString += "bet"; // evaluates to "alphabet" and assigns this value to myString.

Conditional (ternary) operator

The conditional operator is the only JavaScript operator that takes three operands.
The operator can have one of two values based on a condition. The syntax is:

JSCopy to Clipboard

condition ? val1 : val2

If condition is true, the operator has the value of val1. Otherwise it has the value
of val2. You can use the conditional operator anywhere you would use a standard
operator.

For example,

JSCopy to Clipboard

const status = age >= 18 ? "adult" : "minor";

This statement assigns the value "adult" to the variable status if age is eighteen or
more. Otherwise, it assigns the value "minor" to status.

Comma operator
The comma operator (,) evaluates both of its operands and returns the value of the
last operand. This operator is primarily used inside a for loop, to allow multiple
variables to be updated each time through the loop. It is regarded bad style to use it
elsewhere, when it is not necessary. Often two separate statements can and should
be used instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the


following code uses the comma operator to update two variables at once. The code
prints the values of the diagonal elements in the array:

JSCopy to Clipboard

const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];


const a = [x, x, x, x, x];

for (let i = 0, j = 9; i <= j; i++, j--) {


// ^
console.log(`a[${i}][${j}]= ${a[i][j]}`);
}

Unary operators

A unary operation is an operation with only one operand.

delete

The delete operator deletes an object's property. The syntax is:

JSCopy to Clipboard

delete object.property;
delete object[propertyKey];
delete objectName[index];

where object is the name of an object, property is an existing property,


and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to
access it afterwards will yield undefined. The delete operator returns true if the
operation is possible; it returns false if the operation is not possible.

JSCopy to Clipboard
delete Math.PI; // returns false (cannot delete non-configurable properties)

const myObj = { h: 4 };
delete myObj.h; // returns true (can delete user-defined properties)
Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them.
This is, however, regarded as a bad practice — try to avoid it. When you delete an
array property, the array length is not affected and other elements are not re-
indexed. To achieve that behavior, it is much better to just overwrite the element
with the value undefined. To actually manipulate the array, use the various array
methods such as splice.

typeof

The typeof operator returns a string indicating the type of the unevaluated
operand. operand is the string, variable, keyword, or object for which the type is to
be returned. The parentheses are optional.

Suppose you define the following variables:

JSCopy to Clipboard

const myFun = new Function("5 + 2");


const shape = "round";
const size = 1;
const foo = ["Apple", "Mango", "Orange"];
const today = new Date();

The typeof operator returns the following results for these variables:

JSCopy to Clipboard

typeof myFun; // returns "function"


typeof shape; // returns "string"
typeof size; // returns "number"
typeof foo; // returns "object"
typeof today; // returns "object"
typeof doesntExist; // returns "undefined"
For the keywords true and null, the typeof operator returns the following results:

JSCopy to Clipboard

typeof true; // returns "boolean"


typeof null; // returns "object"

For a number or string, the typeof operator returns the following results:

JSCopy to Clipboard

typeof 62; // returns "number"


typeof "Hello world"; // returns "string"

For property values, the typeof operator returns the type of value the property
contains:

JSCopy to Clipboard

typeof document.lastModified; // returns "string"


typeof window.length; // returns "number"
typeof Math.LN2; // returns "number"

For methods and functions, the typeof operator returns results as follows:

JSCopy to Clipboard

typeof blur; // returns "function"


typeof eval; // returns "function"
typeof parseInt; // returns "function"
typeof shape.split; // returns "function"

For predefined objects, the typeof operator returns results as follows:

JSCopy to Clipboard

typeof Date; // returns "function"


typeof Function; // returns "function"
typeof Math; // returns "object"
typeof Option; // returns "function"
typeof String; // returns "function"
void

The void operator specifies an expression to be evaluated without returning a


value. expression is a JavaScript expression to evaluate. The parentheses
surrounding the expression are optional, but it is good style to use them to avoid
precedence issues.

Relational operators

A relational operator compares its operands and returns a Boolean value based on
whether the comparison is true.

in

The in operator returns true if the specified property is in the specified object. The
syntax is:

JSCopy to Clipboard

propNameOrNumber in objectName

where propNameOrNumber is a string, numeric, or symbol expression representing


a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

JSCopy to Clipboard

// Arrays
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees; // returns true
3 in trees; // returns true
6 in trees; // returns false
"bay" in trees; // returns false
// (you must specify the index number, not the value at that index)
"length" in trees; // returns true (length is an Array property)

// built-in objects
"PI" in Math; // returns true
const myString = new String("coral");
"length" in myString; // returns true
// Custom objects
const myCar = { make: "Honda", model: "Accord", year: 1998 };
"make" in myCar; // returns true
"model" in myCar; // returns true

instanceof

The instanceof operator returns true if the specified object is of the specified object
type. The syntax is:

JSCopy to Clipboard

object instanceof objectType

where object is the object to test against objectType, and objectType is a


constructor representing a type, such as Map or Array.

Use instanceof when you need to confirm the type of an object at runtime. For
example, when catching exceptions, you can branch to different exception-
handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether obj is
a Map object. Because obj is a Map object, the statements inside the if block
execute.

JSCopy to Clipboard

const obj = new Map();


if (obj instanceof Map) {
// statements to execute
}

Basic expressions

All operators eventually operate on one or more basic expressions. These basic
expressions include identifiers and literals, but there are a few other kinds as well.
They are briefly introduced below, and their semantics are described in detail in
their respective reference sections.

this
Use the this keyword to refer to the current object. In general, this refers to the
calling object in a method. Use this either with the dot or the bracket notation:

JSCopy to Clipboard

this["propertyName"];
this.propertyName;

Suppose a function called validate validates an object's value property, given the
object and the high and low values:

JSCopy to Clipboard

function validate(obj, lowVal, highVal) {


if (obj.value < lowVal || obj.value > highVal) {
console.log("Invalid Value!");
}
}

You could call validate in each form element's onChange event handler,
using this to pass it to the form element, as in the following example:

HTMLCopy to Clipboard

<p>Enter a number between 18 and 99:</p>


<input type="text" name="age" size="3" onChange="validate(this, 18, 99);" />

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For


example, you can override multiplication and division first, then addition and
subtraction to evaluate addition first.

JSCopy to Clipboard

const a = 1;
const b = 2;
const c = 3;

// default precedence
a + b * c // 7
// evaluated by default like this
a + (b * c) // 7

// now overriding precedence


// addition before multiplication
(a + b) * c // 9

// which is equivalent to
a * c + b * c // 9

Property accessor

The property accessor syntax gets property values on objects, using either dot
notation or bracket notation.

JSCopy to Clipboard

object.property;
object["property"];

The working with objects guide goes into more details about object properties.

Optional chaining

The optional chaining syntax (?.) performs the chained operation on an object if it
is defined and non-null, and otherwise short-circuits the operation and
returns undefined. This allows you to operate on a value that may
be null or undefined without causing a TypeError.

JSCopy to Clipboard

maybeObject?.property;
maybeObject?.[property];
maybeFunction?.();

new

You can use the new operator to create an instance of a user-defined object type or
of one of the built-in object types. Use new as follows:

JSCopy to Clipboard

const objectName = new ObjectType(param1, param2, /* …, */ paramN);


super

The super keyword is used to call functions on an object's parent. It is useful


with classes to call the parent constructor, for example.

JSCopy to Clipboard

super(args); // calls the parent constructor.


super.functionOnParent(args);
Control Statements in JavaScript


JavaScript control statement is used to control the execution of a program based
on a specific condition. If the condition meets then a particular block of action
will be executed otherwise it will execute another block of action that satisfies
that particular condition.
Types of Control Statements in JavaScript
 Conditional Statement: These statements are used for decision-making, a
decision
 n is made by the conditional statement based on an expression that is passed.
Either YES or NO.
 Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement will
keep repeating itself until and unless it is satisfied.
There are several methods that can be used to perform control statements in
JavaScript:
Table of Content
 If Statement
 Using If-Else Statement
 Using Switch Statement
 Using the Ternary Operator (Conditional Operator)
 Using For loop
If Statement
In this approach, we are using an if statement to check a specific condition, the
code block gets executed when the given condition is satisfied.
Syntax:
if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}
Example: In this example, we are using an if statement to check our given
condition.
 Javascript

const num = 5;

if (num > 0) {

console.log("The number is positive.");

};

Output

The number is positive.


If-Else Statement
The if-else statement will perform some action for a specific condition. If the
condition meets then a particular code of action will be executed otherwise it will
execute another code of action that satisfies that particular condition.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Example: In this example, we are using the if..else statement to verify whether
the given number is positive or negative.
 Javascript

let num = -10;


if (num > 0)

console.log("The number is positive.");

else

console.log("The number is negative");

Output

The number is negative


Switch Statement
The switch case statement in JavaScript is also used for decision-making
purposes. In some cases, using the switch case statement is seen to be more
convenient than if-else statements.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example: In this example, we are using the above-explained approach.
 Javascript
let num = 5;

switch (num) {

case 0:

console.log("Number is zero.");

break;

case 1:

console.log("Nuber is one.");

break;

case 2:

console.log("Number is two.");

break;

default:

console.log("Number is greater than 2.");

};

Output

Number is greater than 2.


Ternary Operator (Conditional Operator)
The conditional operator, also referred to as the ternary operator (?:), is a shortcut
for expressing conditional statements in JavaScript.
Syntax:
condition ? value if true : value if false
Example: In this example, we are using the ternary operator to find whether the
given number is positive or negative.
 Javascript

let num = 10;

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

console.log(`The number is ${result}.`);

Output

The number is Positive.


For loop
In this approach, we are using for loop in which the execution of a set of
instructions repeatedly until some condition evaluates and becomes false
Syntax:
for (statement 1; statement 2; statement 3) {
// Code here . . .
}
Example: In this example, we are using Iterative Statement as a for loop, in
which we find the even number between 0 to 10.
 Javascript
for (let i = 0; i <= 10; i++) {

if (i % 2 === 0) {

console.log(i);

};

Output

0
2
4
6
8
10
JavaScript Arrays

An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];

Use of Arrays

If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:

let car1 = "Saab";


let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values
by referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

const array_name = [item1, item2, ...];

It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const.

Example
const cars = ["Saab", "Volvo", "BMW"];

Spaces and line breaks are not important. A declaration can span multiple lines:

Example
const cars = [
"Saab",
"Volvo",
"BMW"
];

You can also create an array, and then provide the elements:

Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

Example
const cars = new Array("Saab", "Volvo", "BMW");

The two examples above do exactly the same.

There is no need to use new Array().

For simplicity, readability and execution speed, use the array literal method.

Accessing Array Elements

You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];

Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

This statement changes the value of the first element in cars:

cars[0] = "Opel";

Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Converting an Array to a String

The JavaScript method toString() converts an array to a string of (comma


separated) array values.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana,Orange,Apple,Mango

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns
"object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns
John:

Array:
const person = ["ab", "", 20];

Objects use names to access its "members". In this


example, person.firstName returns ab:
Object:
const person = {firstName:"ab", lastName:"", age:20};

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

cars.length // Returns the number of elements


cars.sort() // Sorts the array

Array methods are covered in the next chapters.

The length Property

The length property of an array returns the length of an array (the number of array
elements).

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

The length property is always one more than the highest array index.

Accessing the First Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];

Accessing the Last Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];

Looping Array Elements

One way to loop through an array, is using a for loop:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

You can also use the Array.forEach() function:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Adding Array Elements


The easiest way to add a new element to an array is using the push() method:

Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits

New element can also be added to an array using the length property:

Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits

Adding elements with high indexes can create undefined "holes" in an array:

Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"

If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect results.

Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.

 JavaScript does not support associative arrays.


 You should use objects when you want the element names to be strings
(text).
 You should use arrays when you want the element names to be numbers.

JavaScript new Array()

JavaScript has a built-in array constructor new Array().

But you can safely use [] instead.

These two different statements both create a new empty array named points:

const points = new Array();


const points = [];

These two different statements both create a new array containing 6 numbers:

const points = new Array(40, 100, 1, 5, 25, 10);


const points = [40, 100, 1, 5, 25, 10];
The new keyword can produce some unexpected results:

// Create an array with three elements:


const points = new Array(40, 100, 1);

// Create an array with two elements:


const points = new Array(40, 100);

// Create an array with one element ???


const points = new Array(40);

A Common Error
const points = [40];

is not the same as:

const points = new Array(40);

// Create an array with one element:


const points = [40];

// Create an array with 40 undefined elements:


const points = new Array(40);

How to Recognize an Array

A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

const fruits = ["Banana", "Orange", "Apple"];


let type = typeof fruits;

The typeof operator returns object because a JavaScript array is an object.

Solution 1:

To solve this problem ECMAScript 5 (JavaScript 2009) defined a new


method Array.isArray():

Array.isArray(fruits);
Solution 2:

The instanceof operator returns true if an object is created by a given constructor:

const fruits = ["Banana", "Orange", "Apple"];

(fruits instanceof Array);

Nested Arrays and Objects

Values in objects can be arrays, and values in arrays can be objects:

Example
const myObj = {
name: "ab",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}

To access arrays inside arrays, use a for-in loop for each array:

Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).


Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the
"caller":

Example

Calculate the product of two numbers, and return the result:

// Function is called, the return value will end up in x


let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

The () Operator

The () operator invokes (calls) the function:

Example

Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}

let value = toCelsius(77);


Accessing a function with incorrect parameters can return an incorrect answer:

Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}

let value = toCelsius();

Accessing a function without () returns the function and not the function result:

Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}

let value = toCelsius;

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.

Example

Instead of using a variable to store the return value of a function:

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.


Example
// code here can NOT use carName

function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}

// code here can NOT use carName

JavaScript Object Constructors


Object Constructor Functions

Sometimes we need to create many objects of the same type.

To create an object type we use an object constructor function.

It is considered good practice to name constructor functions with an upper-case


first letter.

Object Type Person


function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

Example
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");

const mySelf = new Person("Johnny", "Rally", 22, "green");

Property Default Values

A value given to a property will be a default value for all objects created by the
constructor:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}

Adding a Property to an Object

Adding a property to a created object is easy:

Example
myFather.nationality = "English";

Adding a Property to a Constructor

You can NOT add a new property to an object constructor:

Example
Person.nationality = "English";
To add a new property, you must add it to the constructor function prototype:

Example
Person.prototype.nationality = "English";

Constructor Function Methods

A constructor function can also have methods:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}

Adding a Method to an Object

Adding a method to a created object is easy:

Example
myMother.changeName = function (name) {
this.lastName = name;
}

Adding a Method to a Constructor

You cannot add a new method to an object constructor function.

This code will produce a TypeError:

Example
Person.changeName = function (name) {
this.lastName = name;
}

myMother.changeName("Doe");

TypeError: myMother.changeName is not a function

Adding a new method must be done to the constructor function prototype:

Example
Person.prototype.changeName = function (name) {
this.lastName = name;
}

myMother.changeName("Doe");

Built-in JavaScript Constructors

JavaScript has built-in constructors for all native objects:

new Object() // A new Object object


new Array() // A new Array object
new Map() // A new Map object
new Set() // A new Set object
new Date() // A new Date object
new RegExp() // A new RegExp object
new Function() // A new Function object

Use object literals {} instead of new Object().

Use array literals [] instead of new Array().

Use pattern literals /()/ instead of new RegExp().

Use function expressions () {} instead of new Function().

Example
""; // primitive string
0; // primitive number
false; // primitive boolean

{}; // object object


[]; // array object
/()/ // regexp object
function(){}; // function

JavaScript HTML DOM

With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the
page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create dynamic
HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

The DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

HTML DOM

The HTML DOM is a standard object model and programming interface for
HTML. It defines:

 The HTML elements as objects


 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

Web Browser JS
The web browser environment in JavaScript is the environment in which
JavaScript code runs in a web browser. It's also known as the host environment.
 Provides objects and functions that are specific to the platform
 Allows developers to manipulate the Document Object Model (DOM)
 Allows developers to handle events
 Allows developers to interact with the user
Components
 Window: A global object that represents the browser window and JavaScript code
 Document Object Model (DOM): Represents all page content as objects that can
be modified
How it works
 Browsers like Chrome, Firefox, and Edge have built-in JavaScript engines
 These engines use a public API to create host objects that reflect the DOM into
JavaScript
Examples
 V8: The JavaScript engine used in Chrome
 SpiderMonkey: The JavaScript engine used in Firefox
 Chakra: The JavaScript engine used in Edge
JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:

JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:


HTML Form Example
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

JavaScript Can Validate Numeric Input

JavaScript is often used to validate numeric input:

Please input a number between 1 and 10

Submit

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from
being submitted:

HTML Form Example


<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

Data Validation

Data validation is the process of ensuring that user input is clean, correct, and
useful.

Typical validation tasks are:

 has the user filled in all required fields?


 has the user entered a valid date?
 has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been sent to
the server.

Client side validation is performed by a web browser, before input is sent to a


web server.

HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:

 Constraint validation HTML Input Attributes


 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element


pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

Introduction to JSP
In Java, JSP stands for Jakarta Server Pages( (JSP; formerly JavaServer
Pages)). It is a server-side technology that is used for creating web applications. It
is used to create dynamic web content. JSP consists of both HTML tags and JSP
tags. In this, JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology i.e. a web-based technology that helps us
to create dynamic and platform-independent web pages. In this, Java code can be
inserted in HTML/ XML pages or both. JSP is first converted into a servlet by the
JSP container before processing the client’s request. JSP has various features like
JSP Expressions, JSP tags, JSP Expression Language, etc.
JSP more Advantageous than Servlet
 They are easy to maintain.
 No recompilation or redeployment is required.
 Less coding is required in JSP.
 JSP has access to the entire API of JAVA.
 JSP are extended version of Servlet.
Features of JSP
 Coding in JSP is Easy: As it involves adding Java code to HTML/XML.
 Easy to Use and Learn: It is straightforward and accessible for both Java and
non-Java programmers.
 It Does Not Require Advanced Knowledge of Java: Suitable for users with
basic Java skills.
 Reduction in the Length of Code: JSP uses action tags, custom tags, etc., to
minimize code length.
 Java Scriplets: Allows embedding Java code, variables, and expressions within
JSP pages.
 JSP Expression: Evaluates expressions and converts them to strings.
 Declaration Tag: Used to declare variables and methods within JSP pages.
 Implicit Objects: Provides built-in objects that reduce the length of code.
 Make Interactive Websites: Facilitates the creation of dynamic web pages that
interact with users in real-time.
 Connection to Database is Easier: Simplifies connecting to databases and
allows for easy data reading and writing.
 Extension to Servlet: Inherits all features of servlets and includes implicit
objects and custom tags.
 Portable, Powerful, Flexible, and Easy to Maintain: Browser and server
independent, making it versatile and easy to manage.
 No Redeployment and No Re-Compilation: JSP is dynamic, secure, and
platform-independent, so no need for redeployment or recompilation.
 Create HTML Page from Where Request Will Be Sent: For
example, try.html for sending requests to the server.
 To Handle User Requests, Create .jsp File: For instance, new.jsp for handling
requests.
 Create Project Folder Structure: Organize files and resources into a project
structure.
 Create XML File: For configuration or data, e.g., my.xml.
 Create WAR File: Package the application into a WAR (Web Application
Archive) file for deployment.
 Start Tomcat: Ensure the servlet container (Tomcat) is running.
 Run Application: Deploy and test the JSP application.
 It is Capable of Handling Exceptions: JSP can manage errors and exceptions
effectively.
 Difficult to Debug for Errors: Debugging JSP pages can be challenging due to
their mixed nature of HTML and Java code.
 First-Time Access Leads to Wastage of Time: Initial access can be slower as
JSP pages need to be compiled.
 Output is HTML Which Lacks Features: JSP generates HTML, which may
not support advanced features.
Creating a simple JSP Page
hello.JSP :
JSP simply puts Java inside HTML pages. You can take any existing HTML page
and change its extension to “.jsp” instead of “.html”. In fact, this is the perfect
exercise for your first JSP.
Take the HTML file you used in the previous exercise. change its extension from
“.html” to “jsp”. Now load the new file, with the “.jsp” extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you
reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java
file, compiled, and loaded. This compilation only happens once, so after the first
load, the file doesn’t take long to load anymore. (But every time you change the
JSP file, it will be re-compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We
now proceed to see what makes JSP so useful.
Adding dynamic content via expressions:
As we saw in the previous section, any HTML file can be turned into a JSP file by
changing its extension to .jsp . Of course , what makes JSP useful is the ability to
embed Java. Put the following text in a file. jsp extension (let us call it hello.jsp) ,
place it in your JSP directory, and view it in a browser.
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the
current time. The character sequence.
<%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dynamic HTML pages that
change in response to user actions or vary from user to user.
Explain JSP Elements:
We will learn about the various elements available in JSP with suitable examples.
In JSP elements can be divided into 4 different types.
These are:
 Expression
 Scriplets
 Directives
 Declarations
Expression:
We can use this tag to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.
Syntax:
JSP Expressions are : <%="Anything" %>
NOTE : JSP Expressions start with Syntax of JSP Scriptles are with <%=and ends
with %>. Between these, you can put anything that will convert to the String and
that will be displayed.
Example:
<%="HelloWorld!" %>
Scriplets:
In this tag we can insert any amount of valid java code and these codes are placed
in the _jsp Service method by the JSP engine.
Syntax:
<%//java codes%>
NOTE : JSP Scriptlets begins with <% and ends %> . We can embed any amount
of Java code in the JSP Scriptlets. JSP Engine places these codes in the
_jspService() method.
Variables available to the JSP Scriptlets are:
 Request
 Response
 Session
 Out
Directives:
A JSP “directive” starts with <%@ characters. In the directives, we can import
packages , and define error-handling pages or the session information of the JSP
page.
Syntax:
<%@directive attribute="value"% >
 page
 include
 taglib
Declarations :
This tag is used for defining the functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
NOTE : JSP Declaratives begins with <%! and ends %> with We can embed any
amount of java code in the JSP Declaratives. Variables and functions defined in
the declaratives are class-level and can be used anywhere on the JSP page.
Example :
<%@page import="java.util.*"%>
<HTML>
<BODY>
<%!
Date theDate = new Date(); // Corrected the unwanted space in the declaration
Date getDate() {
System.out.println("In getDate() method");
return theDate;
}
%>
Hello! The time is now <%=getDate()%>
</BODY>
</HTML>
Example of a JSP Web Page:
<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>
<BODY>
<%out.println("Hello there!");%>
</BODY>
</HTML>
Run a Simple JSP Page:
 Step 1: Save the JSP file using “.jsp” extension (ex- “hello.jsp”)
 Step 2: Start the server
 Step 3: Place your application inside a folder
 Step 4: To execute the JSP script, simply start tomcat server and use a browser
to browse an URL of the JSP page i.e.
http://localhost:portnumber/YourApplicationContextRoot/jspfile then you will
see the jsp file is being compiled.
JSP Declaration
Declaration tag is one of the scripting elements in JSP.
This Tag is used for declare the variables. Along with this, Declaration Tag can
also declare method and classes. Jsp initializer scans the code and find the
declaration tag and initializes all the variables, methods, and classes. JSP container
keeps this code outside of the service method (_JSPService()) to make them class
level variables and methods.
Syntax of JSP-Declaration Tag
 HTML

<%! inside this tag we can initialise

our variables, methods and classes %>


Output:

Example of JSP Declaration Tag which initializes a method


 HTML

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http:www.gtbit.org">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>WT</title>

</head>

<body>

<html>

<body>

<%!

int factorial(int n)
{

if (n == 0)

return 1;

return n*factorial(n-1);

%>

<%= "Factorial of 5 is:"+factorial(5) %>

</body>

</html>

</body>

</html>

Difference between the JSP Expression, Declarative, and Scriptlet tags


 Expression tag: This tag contains a scripting language expression that is
converted to a String and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an
expression within text in a JSP file. You cannot use a semicolon to end an
expression.
 Declaration tag: This declares one or more variables or methods for use later
in the JSP source file. It must contain at least one complete statement. You can
declare any number of variables or methods within one declaration tag, but you
have to separate them by semicolons. The declaration must be valid in the
scripting language used in the JSP file.You can add method to the declaration
part.
 Scriptlet tag: You can declare variables in the script-let and can do any
processing. All the Scriptlet go to the inside service() method of the convert
servlet.

JSP Page

A JSP page is a normal web page with JSP elements for generating the parts of the
web page that differ for each request. A simple JSP web page that contains the JSP
elements and template text. Everything on the page that is not a JSP element is
called Template text. Template text can be any text, i.e., HTML, XML, WML or
even plain text.JSP has no dependency on HTML, it can be used with any markup
language. Template text is always passed straight to the browser.
JSP Elements
There are three types of JSP elements present:
1. Directive
2. Action
3. Scripting
New Components were added in JSP 2.0 as an Expression Language(EL) and let’s
call this a fourth element type, even though it’s a bit different than the other three.
1. Directive Elements
page: <%@ page … %>
 Defines page-dependent attributes, such as session tracking, error page, and
buffering requirements.
 is used for importing a package.
 is used for Handling an Exception.
Attributes that we can use are:
 language=”Scripting language” : is used to set which type of language it is.
 import=”import List” : is used to import the packages,and so on…
 session=”true/false”
 contentType=”ctinfo”
 errorPage=”error-url”
 isErrorPage=”true/false”
 info=”information”
 isELIgnored=”true/false”
 isThreadSafe=”true/false”
In all the above “import” attribute can be used many times.
Example:
<%@ page language="java" import="java.util.*,java.sql.*" info="Contact page"
extends="com.rajkumar.User" contextType="text/html"
isELIgnored="false"
isThreadSafe="false" session="false" %>
include: <%@ include … %>
 Includes a file during the translation phase
 for using other JSP pages in the current JSP page
Example:
<%@ include file="filename" %>
<%@ include file="header.jsp" %>
taglib: <%@ taglib … %>
Declares a tag library, containing custom actions, that is used on the page for using
Spring Frameworks
Template Text
Template data refers to the static HTML or XML content of the JSP. Aside from
the usual substitutions, such as those based on quoting and escape sequences, the
template data is written verbatim as part of the JSP response.
2. Action Tag/Element
JSP Action tags or Elements are used to perform some specific tasks. The action
tags are used to control the flow between pages and to use Java Beans. There are
many JSP action tags.
 jsp:forward: forwards the request and response to another resource.
 jsp:include: includes another resource.
 jsp:useBean: creates or locates bean object.
 jsp:setProperty: sets the value of property in bean object.
 jsp:getProperty: prints the value of the property of the bean.
 jsp:plugin: embeds another component such as applet.
 jsp:param: sets the parameter value. It is used in forward and includes mostly.
 jsp:fallback: can be used to print the message if the plugin is working. It is
used in jsp:plugin.
3. Scripting Element
Scriptlet elements must be written within the <% … %> tags.The Scriptlet tag
allows writing Java code statements within the JSP page.The tag is responsible for
implementing the functionality of “_jspService()” by scripting the java code.The
JSP engine will process any code written within the pair of <% and %> tags and
any other code is treated as plain text while translating the JSP page. There are
three main subdivisions of Scripting Elements in Java Server Pages.
 Expression Tag
 Scriptlet Tag
 Declaration Tag
JSP - Architecture

The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes
use of Apache which has built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment
and other services a JSP needs. It knows how to understand the special elements
that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web
application.

JSP Processing

The following steps explain how the web server creates the Webpage using JSP −

 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it
to a JSP engine. This is done by using the URL or JSP page which ends
with .jsp instead of .html.
 The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements
the corresponding dynamic behavior of the page.
 The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
 A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format. The
output is furthur passed on to the web server by the servlet engine inside an HTTP
response.
 The web server forwards the HTTP response to your browser in terms of static
HTML content.
 Finally, the web browser handles the dynamically-generated HTML page inside
the HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file already
exists and whether the modification date on the JSP is older than the servlet. If the
JSP is older than its generated servlet, the JSP container assumes that the JSP
hasn't changed and that the generated servlet still matches the JSP's contents. This
makes the process more efficient than with the other scripting languages (such as
PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having
to be a Java programming wiz. Except for the translation phase, a JSP page is
handled exactly like a regular servlet.

JSP - Directives

A JSP directive affects the overall structure of the servlet class. It usually has the
following form −

<%@ directive attribute = "value" %>

Directives can have a number of attributes which you can list down as key-value
pairs and separated by commas.

The blanks between the @ symbol and the directive name, and between the last
attribute and the closing %>, are optional.

There are three types of directive tag −

S.No. Directive & Description

<%@ page ... %>


1 Defines page-dependent attributes, such as scripting language, error page, and
buffering requirements.

2 <%@ include ... %>


Includes a file during the translation phase.

3 <%@ taglib ... %>


Declares a tag library, containing custom actions, used in the page

JSP - The page Directive

The page directive is used to provide instructions to the container. These


instructions pertain to the current JSP page. You may code page directives
anywhere in your JSP page. By convention, page directives are coded at the top of
the JSP page.
Following is the basic syntax of the page directive −

<%@ page attribute = "value" %>

You can write the XML equivalent of the above syntax as follows −

<jsp:directive.page attribute = "value" />

Attributes

Following table lists out the attributes associated with the page directive −

S.No. Attribute & Purpose

1 buffer
Specifies a buffering model for the output stream.

2 autoFlush
Controls the behavior of the servlet output buffer.

3 contentType
Defines the character encoding scheme.

errorPage
4 Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.

isErrorPage
5 Indicates if this JSP page is a URL specified by another JSP page's errorPage
attribute.

6 extends
Specifies a superclass that the generated servlet must extend.

import
7 Specifies a list of packages or classes for use in the JSP as the Java import
statement does for Java classes.

8 info
Defines a string that can be accessed with the servlet's getServletInfo() method.
9 isThreadSafe
Defines the threading model for the generated servlet.

10 language
Defines the programming language used in the JSP page.

11 session
Specifies whether or not the JSP page participates in HTTP sessions

12 isELIgnored
Specifies whether or not the EL expression within the JSP page will be ignored.

13 isScriptingEnabled
Determines if the scripting elements are allowed for use.

The include Directive

The include directive is used to include a file during the translation phase. This
directive tells the container to merge the content of other external files with the
current JSP during the translation phase. You may code the include directives
anywhere in your JSP page.

The general usage form of this directive is as follows −

<%@ include file = "relative url" >

The filename in the include directive is actually a relative URL. If you just specify
a filename with no associated path, the JSP compiler assumes that the file is in the
same directory as your JSP.

The taglib Directive

The JavaServer Pages API allow you to define custom JSP tags that look like
HTML or XML tags and a tag library is a set of user-defined tags that implement
custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides means for identifying the custom
tags in your JSP page.
The taglib directive follows the syntax given below −

<%@ taglib uri="uri" prefix = "prefixOfTag" >

Here, the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.

<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />


JSP | Expression tag
Expression tag is one of the scripting elements in JSP. Expression Tag in JSP is
used for writing your content on the client-side. We can use this tag for displaying
information on the client’s browser. The JSP Expression tag transforms the code
into an expression statement that converts into a value in the form of a string object
and inserts into the implicit output object.
Syntax: JSP tag
 html

<%= expression %>

Difference between Scriptlet Tag and Expression Tag


 In the Scriptlet tag, it’s Evaluated a Java expression. Does not display any result
in the HTML produced. Variables are declared to have only local scope, so
cannot be accessed from elsewhere in the .jsp. but in Expression Tag it’s
Evaluates a Java expression. Inserts the result (as a string) into the HTML in the
.js
 We don’t need to write out.println in Expression tag for printing anything
because these are converted into out.print() statement and insert it into the
_jspService(-, -) of the servlet class by the container.
JSP code snippets

A JSP code snippet is a code sample that shows you how to add Commerce
functionality to your store. JSP code snippets may be added to a starter store, or to
a store previously published and migrated. JSP code snippets are intended to help
you:

 Quickly add a feature to your store.


 Add a feature that is not included in one of the starter stores.

JSP code snippets use the JSP Standard Tag Library (JSTL). Each JSP code
snippet is well commented, easy to read, easy to understand, and easy to
customize.

Components of the snippet: Each snippet contains Four components


1. Name of the snippet: snippet name that makes unique from different snippets
2. prefix: The keyword which generates current snippets in the program
3. body: The Actual code which we bind to snippets contains in the body.
4. description: Information about the snippet contains in a snippet.
Format of the snippet: Snippet of particular code implemented in the java.json
file which uses JSON format.
 Javascript

"Name_of_the_snippet ":
{

"prefix": "prefix_of_the_snippet",

"body": [

// Actual code of the snippet

],

"description": "description_about_the_snippet"

Procedure: Steps Involved are as follows:


1. Creating and implementing a user-defined class in a new java file.
2. Now, creating a snippet of this class

/* Code for user defined class */

// Importing generic java libraries

import java.util.*;

import java.util.Map.Entry;

import java.io.*;

import java.util.regex.Pattern;

public class GFG {


static class FastReader {

BufferedReader br;

StringTokenizer st;

public FastReader()

br = new BufferedReader(

new InputStreamReader(System.in));

String next()

while (st == null || !st.hasMoreElements()) {

try {

st = new StringTokenizer(br.readLine());

catch (IOException e) {

e.printStackTrace();

}
}

return st.nextToken();

int nextInt() { return Integer.parseInt(next()); }

long nextLong() { return Long.parseLong(next()); }

double nextDouble()

return Double.parseDouble(next());

String nextLine()

String str = "";

try {

str = br.readLine();

catch (IOException e) {
e.printStackTrace();

return str;

public static void main(String[] args)

FastReader scan=new FastReader();

Output:

JSP | Implicit Objects – request and response

JSP stands for Java Server Pages, and it’s a server side technology. It’s used for
creating web applications and dynamic web content. The main property of JSP is
that we can insert our java code inside our HTML page using JSP tag. JSP
provides you platform-independent pages.

 html
<%@ page language = "java" contentType = "text/html; charset = UTF-8"

pageEncoding = "UTF-8"%>

<!DOCTYPE html PUBLIC "-//WT//DTD HTML 4.01

Transitional//EN" "http://www.gtbit.org">

<html>

<head>

<meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">

<title>Insert title here</title>

</head>

<body>

<!-- Here we are going to insert our Java code-->

<% hello to JSP %>

</body>

</html>

Implicit objects are a set of Java objects that the JSP Container makes available to
developers on each page. These objects may be accessed as built-in variables via
scripting elements and can also be accessed programmatically by JavaBeans and
Servlets.JSP provide you Total 9 implicit objects which are as follows
1. request: This is the object of HttpServletRequest class associated with the
request.
2. response: This is the object of HttpServletResponse class associated with the
response to the client.
3. config: This is the object of ServletConfig class associated with the page.
4. application: This is the object of ServletContext class associated with the
application context.
5. session: This is the object of HttpSession class associated with the request.
6. page context: This is the object of PageContext class that encapsulates the use
of server-specific features. This object can be used to find, get or remove an
attribute.
7. page object: The manner we use the keyword this for current object, page
object is used to refer to the current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is
accessed by the respective jsp. The exception implicit object is of
type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println help
for displaying the content to the client.
In this article, two of the main objects which are request and response are
discussed
request Object
The JSP request is an implicit object which is provided by HttpServletRequest. In
the servlet, we have to first import javax.servlet.http.HttpServletRequest then we
have to create its object for taking input from any HTML form as.
Syntax :
import javax.servlet.http.HttpServletRequest;

public class LoginServlet extends HttpServlet


{
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
HttpSession session = request.getSession()
}
}
In JSP, the request object is implicitly defined so that you don’t have to create an
object. JSP request object is created by the web container for each request of the
client. It’s used for getting the parameter value, server name, server port, etc.
In the below example we are using a request object to display the username.

 html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<form action = "Geeks.jsp">

<input type = "text" name = "username">

<input type = "submit" value = "submit"><br/>

</form>

</body>

</html>
response object
This is the HttpServletResponse object associated with the response to the client.
The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date
stamps, HTTP status codes, etc.

 html

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

String name=request.getParameter("username");
out.print("Welcome "+ name);

%>

</body>

</html>

In JSP the response object is implicitly defined, so you don’t have to create an
object. JSP response object is created by the web container for each request of the
client. It basically is used for redirecting to any other resource.
In the below example we use the response object to send the user on
Geeksforgeeks homepage.

 html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>GeeksforGeeks</title>

</head>

<body>

<%
//below line in JSP redirect you to geeksforgeeks page

response.sendRedirect("geeksforgeeks.org");

%>

</body>

</html>

Advantage of JSP over servlet :

 Servlets are difficult to code than JSP. In another way, we can say, JSP is the
replacement for Servlets.
 In Servlets, both static code and dynamic code are put together. In JSP, they are
separated.
 The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets. But in JSP,
they are built-in and are known as implicit objects.
Disadvantage :

 JSP pages require more memory to hold the page.


 The output is in HTML which is not rich for viewers.

JavaBeans

A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other
Java classes −

 It provides a default, no-argument constructor.


 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you
define.

A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation
class −

S.No. Method & Description


getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.

A ead-only attribute will have only a getPropertyName() method, and a write-


only attribute will have only a setPropertyName() method.

JavaBeans Example

Consider a student class with few properties −

package com.tutorialspoint;

public class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

Accessing JavaBeans

The useBean action declares a JavaBean for use in a JSP. Once declared, the

bean becomes a scripting variable that can be accessed by both scripting elements
and other custom tags used in the JSP. The full syntax for the useBean tag is as
follows −

<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>

Here values for the scope attribute can be a page, request, session or application
based on your requirement. The value of the id attribute may be any value as a
long as it is a unique name among other useBean declarations in the same JSP.

Following example shows how to use the useBean action −

<html>
<head>
<title>useBean Example</title>
</head>

<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>

You will receive the following result − −

The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties

Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to
access the get methods and the <jsp:setProperty/> action to access the set
methods. Here is the full syntax −

<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">


<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>

The name attribute references the id of a JavaBean previously introduced to the


JSP by the useBean action. The property attribute is the name of the get or
the set methods that should be invoked.

Following example shows how to access the data using the above syntax −

<html>
<head>
<title>get and set properties Example</title>
</head>

<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student First Name:
<jsp:getProperty name = "students" property = "firstName"/>
</p>

<p>Student Last Name:


<jsp:getProperty name = "students" property = "lastName"/>
</p>

<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>

</body>
</html>

Let us make the StudentsBean.class available in CLASSPATH. Access the above

JSP. the following result will be displayed −

Student First Name:AB

Student Last Name: CD

Student Age: 20
Connection to Database in JSP

A JSP database connection is interfacing Java Server Pages with a database using
JDBC (Java Database Connectivity). JDBC serves as a crucial bridge, enabling
your JSP pages to interact with a database. It uses a Java API that manages
database interactions via Java methods and SQL queries. This functionality is
critical to creating dynamic web applications that require data storage, retrieval,
and manipulation.

Establishing Database Connections

Establishing a database connection in JSP is a multi-step process that involves


several key actions. Each step is crucial for ensuring a secure and efficient
connection to your database. Here's how you can accomplish this:

Import Required Packages

Begin by importing the necessary Java SQL packages in your JSP file. These
packages contain the classes and interfaces required for database operations.

Copy Code<%@ page import="java.sql.*" %>


Loading the JDBC Driver

JDBC drivers are specific to your database, such as MySQL or Oracle. Loading the
driver is your first step in establishing a connection.

Copy Code<%
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
%>
Establishing Connection

Use JDBC to establish a connection to your database. Provide the necessary


credentials and the connection URL to gain access.

Copy Code<%
Connection con = null;
try {
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName",
"username", "password");
// Add your database operations here
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>

Creating Statements

With the connection established, create SQL statements to interact with your
database. This step involves preparing your SQL commands for execution.

Copy CodeStatement stmt = con.createStatement();


Executing Queries

Utilize the created statements for data retrieval, updates, or other SQL operations.

Copy CodeResultSet rs = stmt.executeQuery("SELECT * FROM table_name");


while(rs.next()){
out.println(rs.getString(1));
}
Closing Connections

Closing your database connection, statement, and result set after use is vital. This
practice prevents memory leaks and other issues, ensuring resource efficiency.

Copy Coders.close();
stmt.close();
con.close();

Code Example
Here's a straightforward example demonstrating how to retrieve and display data
from a 'users' database table:

Copy Code<%@ page import="java.sql.*" %>


<html>
<head><title>Database Connection Example</title></head>
<body>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {
// Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");

// Establish Connection
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DatabaseName", "username", "password");

// Create Statement
stmt = con.createStatement();

// Execute Query
rs = stmt.executeQuery("SELECT * FROM users");

// Process Result Set


while(rs.next()) {
out.println("Name: " + rs.getString("name") + "<br>");
}
} catch (ClassNotFoundException e) {
out.println("Driver not found: " + e.getMessage());
} catch (SQLException e) {
out.println("SQL Error: " + e.getMessage());
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {
out.println("Closing Error: " + e.getMessage());
}
}
%>
</body>
</html>

JSP - Session Tracking

 across
as
Pages)
webthey
applications
Session multiple
provides
navigateHTTP
trackingvarious
across
to
is associate
essential
requests,
different
mechanisms
in
requests
web
which
pages
development
towith
are
ofimplement
astateless
web application.
specifictosession
by
users
maintain
nature.
and
tracking,
JSP
retain
user
(JavaServer
state
user
allowing
and
datadata
JSP supports multiple methods for session tracking, including:
 Cookies: A small piece of data stored on the client side by the browser. The
server sends a cookie to the client, which is included in future requests from the
client. Cookies are commonly used for session tracking as they can persist
information even after the user closes the browser.
 URL Rewriting: Involves appending session information directly to the URL.
This method is useful when the client has disabled cookies. The JSP session ID
can be added to the URL using the response.encodeURL() method.
 Hidden Form Fields: Form elements that are not visible to the user but carry
session data from one request to another. These fields can be included in HTML
forms and are used to pass session information when submitting forms.
Implementation of Session Tracking in JSP
We will create a JSP project for session tracking. This example will demonstrate a
simple login system where the user's session is tracked across multiple pages.
Step 1: Create the Dynamic Web Project
Create a new Dynamic Web Project using Eclipse. After creating the project, the
file structure should look like the following:

Step 2: Create the LoginServlet Class


File: LoginServlet.java:
package com.example;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

/**
* Handles POST requests for user login.
*
* @param request HttpServletRequest object containing request details
* @param response HttpServletResponse object to send response
* @throws ServletException If an error occurs during request processing
* @throws IOException If an I/O error occurs
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");

if ("admin".equals(username) && "password".equals(password)) {


HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("dashboard");
} else {
response.sendRedirect("login.jsp");
}
}
}
This servlet handles login requests. If the username and password match "admin"
and "password," it creates a session and redirects to the dashboard. Otherwise, it
redirects back to the login page.
Step 3: Create the DashboardServlet Class
File: DashboardServlet.java:
package com.example;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class DashboardServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

/**
* Handles GET requests to the dashboard page.
*
* @param request HttpServletRequest object containing request details
* @param response HttpServletResponse object to send response
* @throws ServletException If an error occurs during request processing
* @throws IOException If an I/O error occurs
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("username") == null) {
response.sendRedirect("login.jsp");
} else {
request.getRequestDispatcher("dashboard.jsp").forward(request, response);
}
}
}
This servlet handles requests to the dashboard page. It checks if a session exists
and if the username is set. If not, it redirects to the login page; otherwise, it
forwards the request to the dashboard page.
Step 4: Create the LogoutServlet Class
File: LogoutServlet.java:
package com.example;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

/**
* Handles POST requests to log out the user.
*
* @param request HttpServletRequest object containing request details
* @param response HttpServletResponse object to send response
* @throws ServletException If an error occurs during request processing
* @throws IOException If an I/O error occurs
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.sendRedirect("logout.jsp");
}
}
This servlet handles logout requests. It invalidates the session and redirects to the
logout page.
Step 5: Create the Login Page
File: login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Login</h2>
<form action="login" method="post">
<input type="text" name="username" placeholder="Enter Username"
required>
<input type="password" name="password" placeholder="Enter Password"
required>
<input type="submit" value="Login"> <!-- Button text is "Login" -->
</form>
</div>
</body>
</html>
This JSP page provides a form for users to enter their username and password. The
form submits a POST request to the LoginServlet.
Step 6: Create the Dashboard Page
File: dashboard.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page session="true" %>
<%
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<html>
<head>
<title>Dashboard</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Welcome, <%= username %>!</h2>
<p>This is your dashboard.</p>
<form action="logout" method="post">
<input type="submit" value="Logout">
</form>
</div>
</body>
</html>
This JSP page displays a welcome message to the logged-in user. If the session is
invalid or the username is not set, it redirects to the login page. Otherwise, it shows
the dashboard and provides a logout button.
Step 7: Create the Logout Page
File: logout.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Logout</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>You have successfully logged out.</h2>
<a href="login.jsp">Login again</a>
</div>
</body>
</html>
This JSP page informs the user that they have successfully logged out and provides
a link to log in again.
Step 8: Create the StyleSheet
File: style.css:
body {
background-color: #f0f8f7;
font-family: Arial, sans-serif;
}

.container {
width: 30%;
margin: 100px auto;
background-color: #d8f3dc;
border-radius: 10px;
padding: 20px;
box-shadow: 0px 0px 10px #333;
}

h2 {
color: #40916c;
text-align: center;
}

input[type="text"], input[type="password"], input[type="submit"] {


width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 5px;
}

input[type="submit"] {
background-color: #40916c;
color: #fff;
border: none;
}
This CSS file styles the JSP pages. It includes styling for the background,
container, headers, and form elements.
Step 9: Configure the web.xml
File: web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" id="WebApp_ID"
version="6.0">
<display-name>SessionTrackingExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.example.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>DashboardServlet</servlet-name>
<servlet-class>com.example.DashboardServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DashboardServlet</servlet-name>
<url-pattern>/dashboard</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.example.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout> <!-- Timeout in minutes -->
</session-config>

</web-app>
This configuration file maps the servlets to their respective URL patterns. It tells
the server which servlet to use for each URL pattern.
Step 10: Run the Project
Output:
1. Login Page:
2. Dashboard:
3. Logout page:

Advantages of JSP Session Tracking


1. Maintains User State Across Requests HTTP is a stateless protocol, meaning
each request is independent. Session tracking allows for maintaining user state
across multiple HTTP requests, making it possible to store and retrieve user
data (such as login credentials and preferences) during the session.
2. Simplified User Experience Session tracking enables a smoother user
experience by preserving user interactions and choices across pages. For
example, it can maintain the contents of a shopping cart on e-commerce
websites, keep form data in multi-step forms, or retain login status.
3. Scalable and Efficient JSP provides multiple session tracking methods, which
can be optimized based on project needs:
 Cookies: Stored on the client’s browser, cookies do not increase server load.
 URL Rewriting and Hidden Fields: Useful when cookies are disabled,
offering flexibility in maintaining session state.
4. Easy Session Management The HttpSession API in JSP makes it easy to
create, store, retrieve, and invalidate session data, reducing the complexity of
state management in web applications. Sessions can also be customized to
expire after a certain period of inactivity, enhancing security and resource
management.
5. Security Mechanisms Session tracking helps implement security mechanisms,
such as login authentication, by maintaining the session of authenticated users
across multiple pages. It also allows for session timeouts, which enhance
security.
6. Robust Error Handling JSP’s session management can be configured to
handle session failures gracefully, ensuring the application does not crash when
a session is invalid or expires. It can redirect users to the login page or prompt
them to reauthenticate.

You might also like