0% found this document useful (0 votes)
31 views70 pages

Comprehensive Guide to JavaScript Basics

javascript

Uploaded by

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

Comprehensive Guide to JavaScript Basics

javascript

Uploaded by

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

JavaScript

Computer – TE – Internet Programming


Shraddha R. Kawji
Assistant Professor
Computer
SIES Graduate School of Technology

1
Faculty Name
Introduction to JavaScript

• Initially when JS was invented by Brendan Eich in 1995,


• It was supposed to function only as a scripting language on the
client side for web development.

• However, JS has evolved and diversified a lot in many other


domains like - Server side programming, Desktop application
development, Mobile Application development, Virtual Reality,
Machine Learning etc.

2
Faculty Name
3
Faculty Name
Key Features of JavaScript

•Client-side scripting: Runs in the browser without needing


a server.
•Interactivity: Enables user interactions such as clicks, input
validation, popups, etc.
•Dynamism: Can modify HTML and CSS on the fly (DOM
manipulation).
•Lightweight & Fast: Executes quickly in the browser
environment.
•Cross-platform: Works on all major browsers and
platforms.

4
Faculty Name
Application of JavaScript

1. Web Development (Client-side)


• DOM Manipulation: Change HTML content, styles, and structure
dynamically.
• Form Validation: Check user inputs before submitting to the server.
• Animations & Effects: Slideshows, fades, transitions, etc.
• Interactive Elements: Pop-ups, drop-downs, tooltips, etc

2. Web Development (Server-side)


• Using [Link], JavaScript can run on the server:
• Handle backend logic
• Connect to databases
• Serve APIs and files

5
Faculty Name
Client Server
Featur -Side -Side
e Script Script
ing ing
Runs
Runs
on the
Defini on the
user’s
tion web
brows
server
er
Proce
ssed
Proce on
ssed the
on server
Execu the befor
tion client e
device sendi
(brow ng to
ser) the
brows
er
Slowe
Gener
r,
ally
involv
faster
es
since
reques
Speed it
t and
doesn’
respon
t need
se
server
with
calls
server
Can
Can’t
acces
acces
s
s
Acces datab
server
s to ases,
files
Files server
or
files,
datab
and
ases
APIs
Less
secure
More
(user
secure
can
(code
see
Securi is
the
ty hidden
code
from
using
the
brows
user)
er
tools)
PHP,
ASP.N
ET,
JavaS Python
Exam cript, (Djang
ples HTML o),

Feature Client-Side Scripting Server-Side Scripting


, CSS Node.j
s,
Java
(JSP)
Login
Form handli
validat ng,
ion, databa
Use animat se
Cases ions, acces
UI s,
interac sendin
tions g
emails
Output
Output
is sent
is
from
directl
server
Outp y
as
ut visible
HTML
in
,
brows
JSON,
er
etc.

Definition Runs on the user’s browser Runs on the web server


Depen
Depen
ds on
Depe ds on
brows
ndenc web
er
y server
capabi
setup
lity

Processed on the server before


Execution Processed on the client device (browser)
sending to the browser

Generally faster since it doesn’t need Slower, involves request and


Speed
server calls response with server
Can access databases, server files,
Access to Files Can’t access server files or databases
and APIs
Less secure (user can see the code using More secure (code is hidden from the
Security
browser tools) user)
PHP, [Link], Python (Django),
Examples JavaScript, HTML, CSS
[Link], Java (JSP)
Login handling, database access,
Use Cases Form validation, animations, UI interactions
sending emails
Output is sent from server as HTML,
Output Output is directly visible in browser
JSON, etc.

Dependency Depends on browser capability Depends on web server setup

6
Faculty Name
How to Add JavaScript

7
Faculty Name
Embedded of JavaScript

<!DOCTYPE html>
<html>
<head>
<title>Hello JavaScript</title>
</head>
<body>

<script>
[Link]("Hello, World!");
</script>
</body>
</html>

8
Faculty Name
External JavaScript File

9
Faculty Name
Variable

A variable in JavaScript is a named container used to store data


values that can be changed or reused in a program.

Variables help you:


• Store values like numbers, strings, or objects.
• Reuse and manipulate data.
• Make your code dynamic and interactive.

let name = "Shraddha"; // string value


var age = 25; // number value
const PI = 3.14; // constant value

10
Faculty Name
Data Descri Exam
Type ption ple
"Hello
Textua ",
String
l data 'JavaS
cript'
Nume
ric
42,
Numb data
3.14, -
er (intege
7
r or
float)
Very
12345
large
67890
integer
BigInt 12345
s
67890
(ES20
n
20+)
Logica
l
Boole true,
value:
an false
true or
false
A
variabl
e
declar
Undef undefi
ed but
ined ned
not
assign
ed a
value
Repre
sents
no
Null value null
or
empty
value
Uniqu
e and
Symb
Symb immut
ol("id"
ol able
)
value
(ES6)

JavaScript Primitive Data Types

Data Type Description Example


String Textual data "Hello", 'JavaScript'
Number Numeric data (integer or float) 42, 3.14, -7
Very large integers 12345678901234567
BigInt
(ES2020+) 890n
Boolean Logical value: true or false true, false
A variable declared but not
Undefined undefined
assigned a value
Represents no value or
Null null
empty value
Unique and immutable value
Symbol Symbol("id")
(ES6)

11
Faculty Name
Reass
Keywo Hoisti Use
Scope ignabl
rd ng Case
e
Older
JS,
Functi less
var ✅ Yes ✅ Yes
on recom
mende
d
Moder
n
let Block ✅ Yes ❌ No usage,
flexibl
e
For
consta
nts
const Block ❌ No ❌ No
(uncha
ngeabl
e)

Types of Variable Declarations

Keyword Scope Reassignable Hoisting Use Case


Older JS,
less
var Function ✅ Yes ✅ Yes
recommende
d
Modern
let Block ✅ Yes ❌ No usage,
flexible
For constants
const Block ❌ No ❌ No (unchangeabl
e)

12
Faculty Name
Example of variable

let name = "Shraddha"; // String


let age = 25; // Number
let isStudent = true; // Boolean
let x; // Undefined
let value = null; // Null
let bigNum = 1234567890n; // BigInt
let id = Symbol("id"); // Symbol

13
Faculty Name
Descri Exam
Type
ption ple
1.
Perfor
Arith +, -,
m
metic *, /, %,
basic
Opera **
math
tors
2.
Assign
Assig
values =, +=,
nmen
to -=, *=,
t
variabl /=
Opera
es
tors
Comp
3. are
Comp values ==,
arison and ===, !
Opera return =, >, <
tors true or
false
4. Combi
Logic ne
al boolea &&, `
Opera n
tors values
5. Perfor
Bitwis m bit-
e level &, `
Opera operati
tors ons
6.
Conca
String
tenate +
Opera
strings
tors
7. Check
typeof,
Type type of
instan
Opera variabl
ceof
tors e
8.
Short- conditi
Ternar
hand on ?
y
for if- expr1 :
Opera
else expr2
tor
Defaul
9.
t value
Nullis a ??
when
h default
null or
Coale Value
undefi
scing
ned
...
10. Expan
(sprea
Sprea d or
d/rest
d/ collect
operat

Operators in JavaScript
Rest values
or)

Type Description Example


1. Arithmetic
Perform basic math +, -, *, /, %, **
Operators
2. Assignment
Assign values to variables =, +=, -=, *=, /=
Operators
3. Comparison Compare values and return
==, ===, !=, >, <
Operators true or false
4. Logical Operators Combine boolean values &&, ||,!
5. Bitwise Operators Perform bit-level operations &, |,^,~,<<,>>
6. String Operators Concatenate strings +
7. Type Operators Check type of variable typeof
8. Ternary Operator Short-hand for if-else condition ? expr1 : expr2

14
Faculty Name
Descri Exam
Type
ption ple
Execut
1.
e code if, else
Condi
based if,
tional
on else,
State
conditi switch
ments
ons
2. Repea
for,
Loopi t code
while,
ng multipl
do...w
State e
hile
ments times
Chang
e
3. break,
norma
Jump contin
l flow
State ue,
of
ments return
execut
ion

Control Flow Statements in JavaScript

Control flow statements control the order in which instructions or code blocks are
executed based on conditions or loops.

Type Description Example


1. Conditional Execute code based
if, else if, else if ladder, switch
Statements on conditions
2. Looping Repeat code multiple
for, while, do...while
Statements times

15
Faculty Name
if Statement
Syntax

if (condition) {
// code to execute if condition is true
}

Example:

let age = 20;

if (age >= 18) {


[Link]("You are eligible to vote.");
}

16
Faculty Name
If-else statement
if (condition) {
// code if condition is true
} else {
// code if condition is false
}

Example:

let age = 16;

if (age >= 18) {


[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote.");
}

17
Faculty Name
if...else if...else
Statement
Syntax:

if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if all conditions are false Example:
}
let marks = 85;

if (marks >= 90) {


[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
} 18
Faculty Name
Switch Statement
switch(expression) {
case value1:
// code to execute if expression === value1
break;
case value2:
// code to execute if expression === value2
break; Example:
// more cases...
default: let day = 2;
// code if no case matches
} switch(day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
} 19
Faculty Name
while
Loop

syntax
while (condition) {
// code block to be executed
}

let i = 1;
while (i <= 5) {
[Link]("Number: " + i);
i++;
}

20
Faculty Name
do...while
Loop

Syntax
do {
// code block to be executed
} while (condition);

Example

let i = 1;
do {
[Link]("Value: " + i);
i++;
} while (i <= 5);

21
Faculty Name
For loop

Sytnax

for (initialization; condition;


increment/decrement) {
// code to execute each time the loop runs
}

Example
for (let i = 1; i <= 5; i++) {
[Link]("Number: " + i);
}

22
Faculty Name
Pop-
Functi Button Return
up
onality s Value
Type
Displa
y
alert() OK None
messa
ge
Ask
OK /
confir for true /
Cance
m() confir false
l
mation
Ask
OK / Input
promp for
Cance string /
t() user
l null
input

POPUp Boxes

JavaScript provides 3 main types of pop-up boxes (also called dialog boxes)
used to interact with users through the browser.

Pop-up Type Functionality Buttons Return Value


alert() Display message OK None
Ask for
confirm() OK / Cancel true / false
confirmation
prompt() Ask for user input OK / Cancel Input string / null

23
Faculty Name
alert() Box
🔹 Purpose:
Displays an informational message with an OK button.
• Stops code execution until the user clicks OK
• Used to show warnings or info messages

🔹 Syntax:

alert("This is an alert box!");

24
Faculty Name
confirm() Box
🔹 Purpose:
Asks the user to confirm something with OK or Cancel
buttons.
🔹 Syntax:
<script>
let result = confirm("Do you want to continue?");
if (result) {
alert("You chose OK.");
} else {
alert("You clicked Cancel.");
}
</script>

25
Faculty Name
prompt()
Box
• Prompts the user to input a value.
• The value entered by the user
• null if the user clicks Cancel

<script>
let name = prompt("What is your name?");
if (name != null) {
alert("Hello, " + name + "!");
}
</script>

26
Faculty Name
Function
• A function in JavaScript is a block of reusable code designed to perform
a specific task. It helps organize code, avoid repetition, and improve
readability and maintainability.
• Functions are one of the fundamental building blocks in JavaScript.
• A function is a JavaScript procedure—a set of statements that performs a
task or calculates a value.
• 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).

Why Use Functions?


• Reuse code multiple times
• Break program into smaller tasks
• Improve modularity and debugging
27
Faculty Name
28
Faculty Name
<!DOCTYPE html>
<html>
<head>
<title>Simple Function</title>
</head>
<body>

<h2>Simple JavaScript Function</h2>

<button onclick="sayHello()">Click
Me</button>

<script>
function sayHello() {
alert("Hello, welcome to JavaScript!");
}
</script>

</body>
</html>
29
Faculty Name
Object in JavaScript

• An Object in JavaScript is a fundamental data type used to store


collections of data and more complex entities.
• It groups related data and functionality (in the form of properties and
methods) together.
• Properties are key-value pairs that store data.
• Methods are functions that belong to the object.

Think of an object like a real-world object —


• a car might have
properties like color, model, year,
methods like start(), stop().

30
Faculty Name
Create a object in Javascript

Syntax1: Syntax 2:by creating a new object

var obj = { var obj = new Object();


key1: value1,
obj.key1 = value1;
key2: value2,
// ... obj.key2 = value2;
};

Syntax 3:using constructor


function Person(name, age) {
[Link] = name;
[Link] = age;
}

const person1 = new Person("Bob", 25);

31
Faculty Name
Date object

• The JavaScript date object can be used to get year, month and
day. You can display a timer on the webpage by the help of
JavaScript date object.
• Date()
• Date(milliseconds)
• Date(dateString)
• Date(year, month, day, hours, minutes, seconds, milliseconds)

Faculty Name
JavaScript Date Methods

getDate()It returns the integer value between 1 and 31 that represents the day
for the specified date.
getDay()It returns the integer value between 0 and 6 that represents the day of
the week.
getFullYear()It returns the integer value that represents the year.
getHours()It returns the integer value between 0 and 23 that represents the
hours.
getMilliseconds()It returns the integer value between 0 and 999 that represents
the milliseconds.
getMinutes()It returns the integer value between 0 and 59 that represents the
minutes.
getMonth()It returns the integer value between 0 and 11 that represents the
month.
getSecondsIt returns the integer value between 0 and 60 that represents the
seconds.

Faculty Name
Math Object
• The JavaScript math object provides several constants and methods to perform
mathematical operation.
• Unlike date object, it doesn't have constructors.

Faculty Name
Math Object Methods

abs() It returns the absolute value of the given number.


acos() It returns the arccosine of the given number in
radians.
asin() It returns the arcsine of the given number in radians.
atan() It returns the arc-tangent of the given number in
radians.
cbrt() It returns the cube root of the given number.
ceil() It returns a smallest integer value, greater than or
equal to the given number.
cos() It returns the cosine of the given number.
cosh() It returns the hyperbolic cosine of the given number.

Faculty Name
exp() It returns the exponential form of the given number.
floor() It returns largest integer value, lower than or equal to the given
number.
hypot() It returns square root of sum of the squares of given numbers.
log() It returns natural logarithm of a number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
random() It returns random number between 0 (inclusive) and 1
(exclusive).
round() It returns closest integer value of the given number.
sign() It returns the sign of the given number
sin() It returns the sine of the given number.
sinh() It returns the hyperbolic sine of the given number.
sqrt() It returns the square root of the given number
tan() It returns the tangent of the given number.
tanh() It returns the hyperbolic tangent of the given number.
Faculty Name
Regular Expression Object

• Regular expressions are a way to describe patterns in a string


of data.
• Regular expressions allow you to check a string of characters
like an e-mail address or password for patterns to see if they
match the pattern defined by that regular expression and
produce actionable information.
• It can either be created with a RegExp constructor, or by using
forward slashes ( / ) to enclose the pattern.

37
Faculty Name
Descri
Flag Name
ption
Find
all
match
g Global es, not
just
the
first
Case-
Ignore insens
i
case itive
match
^ and
$
match
Multili
m start/e
ne
nd of
each
line
.
match
es
newlin
s Dot all
e
charac
ters as
well
Enable
s full
Unico Unico
u
de de
matchi
ng
Match
must
start
y Sticky exactl
y at
lastIn
dex

Flag in Regular Expression

Flags are optional modifiers that change how the regular expression
behaves.

Flag Name Description


g Global Find all matches, not just the first
i Ignore case Case-insensitive match
m Multiline ^ and $ match start/end of each line

38
Faculty Name
Syntax
new RegExp("pattern", "flags");

39
Faculty Name
Ranges

Ranges [a-z]
• If we want to match all of the letters of an alphabet
in a single position, we could write all the letters
inside the brackets. But there is an easier way, and
that is ranges.
• For example, [a-h] will match all the letters from a to
h. Ranges can also be digits like [0-9] or capital
letters like [A-Z].

Faculty Name
Faculty Name
Quantifiers
.
Quantifiers are symbols that have a special meaning in a regular expression.
• +: Matches the preceding expression one or more times.

• ^: Matches the beginning of the string, the regular expression that follows it
should be at the start of the test string, i.e the caret (^) matches the start of the
string

• $: Matches the end of the string. That is, the regular expression that precedes it
should be at the end of the test string. The dollar ($) sign matches the end of the
string.

• {N}: Matches exactly N occurrences of the preceding regular expression.

• {N,}: Matches at least N occurrences of the preceding regular expression.


• {N,M}: Matches at least N occurrences and at most M
occurrences of the preceding regular expression, where M > N.
• Alternation X|Y : Matches either X or Y. For example:

Faculty Name
Meani
Part
ng
Start
^ of
input
One or
more
[a-zA- valid
Z0-9._ userna
%+-]+ me
charac
ters
Must
have
@ an @
symbo
l
Domai
n
[a-z0- name
9.-]+ (e.g.,
gmail,
yahoo)
Dot
before
\.
extens
ion
Extens
ion
[a-z] (e.g.,
{2,} com,
org,
in)
End of
$
input
Case-
i insens
itive

1. Email Address
🔹 Regular Expression:

/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i
Part Meaning
^ Start of input
[a-zA-Z0-9._%+-]+ One or more valid username characters
@ Must have an @ symbol
[a-z0-9.-]+ Domain name (e.g., gmail, yahoo)
\. Dot before extension
[a-z]{2,} Extension (e.g., com, org, in)
$ End of input
i Case-insensitive

✅ Matches: ❌ Does Not Match:


•abc123@[Link] • abc@.com
•[Link]@[Link] • @[Link]
43
Faculty Name
Meani
Part
ng
^ Start
`(?:
0)?`
+91
Starts
[6-9] with
6–9
Follow
ed by
\d{9}
9
digits
$ End

Indian Phone Number


🔹 Regular Expression:

/^(\+91|0)?[0-9]\d{10}$/

Part Meaning
^ Start
`(+91 0)
[6-9] Starts with 6–9
\d{9} Followed by 9 digits
$ End

✅ Matches: ❌ Does Not Match:


•9876543210 •1234567890
•09876543210 •+929876543210 (wrong country code)
•+919876543210

44
Faculty Name
45
Faculty Name
Browser Object in JavaScript

The Browser Object Model (BOM) in JavaScript allows you to interact with the
browser window and control browser-related features that are not part of the web
page (DOM),

•Opening new windows


•Getting the browser's size
•Redirecting the page
•Working with history and location
•Showing alerts, confirms, and prompts

46
Faculty Name
Descri
Object
ption
Top-
level
object
repres
windo enting
w the
brows
er
windo
w
Provid
es
inform
naviga ation
tor about
the
brows
er
Provid
es
inform
ation
screen
about
the
user’s
screen
Contai
ns info
locatio about
n the
curren
t URL
Allows
naviga
tion
throug
history
h the
sessio
n
history
Repre
sents
the

Object Description
page
docum
(part
ent
of
DOM,
not
BOM)

window Top-level object representing the browser window


navigator Provides information about the browser
screen Provides information about the user’s screen
location Contains info about the current URL
history Allows navigation through the session history
document Represents the page (part of DOM, not BOM)

Object Key Properties / Methods Purpose


window alert(), setTimeout() Browser-level interaction
navigator userAgent, language Browser/device information
screen width, height, colorDepth Physical screen info
location href, hostname, reload() URL control and redirects
history back(), forward(), length Navigation history

47
Faculty Name
Document Object Model

• Document: Represents the entire web page, acting


as the root of the DOM tree.

• Objects: HTML elements are treated as objects,


allowing JavaScript to access and modify their
properties and attributes.

• Model: The document is organized into a


hierarchical tree structure, where each element is a
node, and nodes have relationships (parent, child,
sibling). This structure enables navigation and
targeting of specific elements.

48
Faculty Name
Metho Descri
d ption
Return
s the
getEle eleme
mentB nt with
yId(id) the
given
ID
Return
sa
getEle collect
ments ion of
ByCla eleme
ssNa nts
me(cl with
ass) the
given
class
Return
sa
collect
getEle ion of
ments eleme
ByTag nts
Name with
(tag) the
given
tag
name
Return
s the
first
query eleme
Select nt that
or(sel match
ector) es a
CSS
select
or
Return
s all
query eleme
Select nts
orAll(s that
elector match
) a CSS
select
or
Create
sa
create
new
Eleme
HTML
nt(tag)
eleme
nt
Create
create
sa
TextN
new
ode(te
text
xt)
node
Adds a
node
appen to the
dChild end of
(node) a
parent
node
Writes
directl
y to
the
docum
ent
write(t (not
ext) recom
mende
d for
dynam
ic
conten
t)

Method Description

getElementById(id) Returns the element with the given ID

Returns a collection of elements with


getElementsByClassName(class)
the given class

Returns a collection of elements with


getElementsByTagName(tag)
the given tag name

Writes directly to the document (not


write(text)
recommended for dynamic content)

writeln(text) Write the specified string in the


document with new line
49
Faculty Name
[Link]()
The [Link]() method returns the element
of specified id.

Example:
<script type="text/javascript">
function getcube()
{
var number=[Link]("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

Faculty Name
getElementsByClassName()
The getElementsByClassName() method is used for selecting
or getting the elements through their class name value.

Syntax
var ele = [Link]('name');

Faculty Name
[Link]() method
The [Link]() method returns all the element of
specified name.

Example:
<script type="text/javascript">
function totalelements()
{
var allgenders=[Link]("gender");
alert("Total Genders:"+[Link]);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>

Faculty Name
[Link]()
The [Link]() method returns all the
element of specified tag name.

Syntax:
[Link]("name")

Faculty Name
Adding and Deleting Elements

• [Link](element):Create an HTML element

• [Link](element)Remove an HTML element

• [Link](element)Add an HTML element

• [Link](element)Replace an HTML element

• [Link](text)

Faculty Name
Event Handling :Controlling Windows & Frames

What is an Event:
• JS interactions with HTML are handled through events that occur when
user or browser manipulates the page.
Events:
Loading a page
clicking a button
pressing a key
resizing frame window
closing a window
• Developers can use these events to execute JS coded responses.

Faculty Name
Reacting to Events

• A JavaScript can be executed when an event occurs, like when a user clicks
on an HTML element.
• To execute code when a user clicks on an element, add JavaScript code to
an HTML event attribute:
onclick=JavaScript

Examples of HTML events:


• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key

Faculty Name
Attribute Description
ondblclick Script runs when a mouse double-click

onmousedown Script runs when mouse button is pressed

onmousemove Script runs when mouse pointer moves

onmouseout Script runs when mouse pointer moves out of


an element
onmouseover Script runs when mouse pointer moves over an
element
onmouseup Script runs when mouse button is released

Faculty Name
Form Validation using Javascript

Form validation is the process of checking whether the data entered


into a web form is complete, correct, and useful before it is sent to a
server for processing.

Why is Form Validation Important?


• Ensures the user enters required and correctly formatted
data.
• Prevents errors in backend systems.
• Improves user experience by giving immediate feedback.
• Helps protect against malicious input (e.g. SQL injection,
script injection).

58
Faculty Name
Types of Form Validation

1. Client-side validation
• Happens in the browser using JavaScript or HTML5 attributes.
• Provides instant feedback.
• Can prevent unnecessary server requests.
• But: It can be bypassed, so it’s not secure on its own.

2. Server-side validation
• Happens on the server after the form is submitted.
• Ensures security and data integrity.
• Always required, even if client-side validation is used.

59
Faculty Name
1. Accept name and password from user and validate the data as
follows: The name should not be empty, password should not be
less than 6 character

2. Write a JavaScript code to check password and confirm password

3. Write a JavaScript code to validate the text filed for numeric value
only. Use NaN() function.

4. Accept email id from user and check with following criteria: Email
must contain .(dot) character and @ symbol. There should be min 2
character after the .(dot)

5. Write down JavaScript code to check mobile number(number


should start with 9 or 8) and mail id (check @ and .)

6. Write JavaScript code to validate user name and password


(password length must be in between 6-12 character and username
should not be start with _,@ or any other symbol)

60
Faculty Name
Exception Handling in JavaScript

• Exceptional handling is the process or method used to handle abnormal statement


in the code and executing them.
• Exception handling in JavaScript is a mechanism to deal with runtime errors that
would otherwise crash your program.
• For example ,the Division of non-zero value with zero will result always infinity, and it
is in exception, Thus with exception handling it can be executed
• In exception handling a throw statement is used to raised an exception. It means
when an abnormal condition occurs an exception is thrown using throw keyword

• Syntax

try {
// Code that may cause an error
}
catch (error) {
// Handle the error
}
finally {
// Always executed (optional)
} Faculty Name
61
try...catch...finally
.
try:
•This block contains the code that might throw an error.
• If an error occurs within this block, the program's execution is immediately
stopped, and control is passed to the catch block.

catch:
• This block is executed only when an error occurs in the try block.
• It receives the error object as a parameter, which contains details about the error
that occurred.
• You can use this block to log the error, display a user-friendly message, or perform
other necessary recovery actions.

finally:
• This block is always executed, whether an error occurred or not. It's often used for
cleanup tasks, such as closing files or database connections, ensuring that these
operations happen regardless of the outcome of the try block.
• The finally block is optional.

62
Faculty Name
Types of Error

1. Syntax Error
2. Runtime Error
3. Logical Error

63
Faculty Name
Syntax Errors

• When user makes a mistake in the predefining syntax of programing language a


syntax error may appear
• These occur when the code violates JavaScript’s grammar rules.
• They are detected before the code runs.

• Example
[Link]("Hello World" // Missing closing parenthesis

64
Faculty Name
Runtime Errors

• When an error occurs during the execution of program ,such an error is known
as runtime [Link] code which creates runtime error known as
Exceptions ,Thus exception handler are used for handling runtime error
• These occur while the program is running.
• They happen when the code is syntactically correct but something goes wrong
during execution.

Example
let num = 10;
[Link]([Link]());

65
Faculty Name
Logical Error

Logical Error
• An error occurs when there is any logical mistake in the program that
may not produce the desire output ,and may terminate abnormally
such error is known as logical error

Example
function findAverage(a, b) {
return a + b / 2; // ❌ Wrong logic due to missing parentheses
}

[Link](findAverage(10, 20)); // Output: 20 (Incorrect)

66
Faculty Name
Example of Javascript

try {
[Link](myVar);

let num = 123;


[Link]();
}
catch (error)
{
[Link]([Link] + ": " + [Link]);
}

67
Faculty Name
DHTML JavaScript
• DHTML stands for Dynamic HTML. Dynamic means that the
content of the web page can be customized or changed according
to user inputs i.e. a page that is interactive with the user.
• In earlier times, HTML was used to create a static page. It only
defined the structure of the content that was displayed on the
page. With the help of CSS, we can beautify the HTML page by
changing various properties like text size, background color, etc.
• DHTML included JavaScript along with HTML and CSS to make the
page dynamic.
• This combo made the web pages dynamic and eliminated the
problem of creating static pages for each user.
• To integrate JavaScript into HTML, a Document Object
Model(DOM) is made for the HTML document. In DOM, the
document is represented as nodes and objects which are
accessed by different languages like JavaScript to manipulate the
document.

68
Faculty Name
Featu DHT
HTML
re ML
Dyna
Hyper mic
Text Hyper
Full Marku Text
Form p Marku
Langu p
age Langu
age
A
A combi
standa nation
rd of
marku HTML
p , CSS,
langua JavaS
ge cript,
Defini used and
tion to DOM
create to
the create
basic interac
structu tive
re of and
web dynam
pages. ic web
pages.
Dyna
mic –
Static
conten

t,
conten
style,
t does
and
not
structu
Natur chang
re can
e e
chang
withou
e
t
withou
reloadi
t
ng the
reloadi
page.
ng the
page.
HTML
+ CSS
Techn Only
+
ology HTML
JavaS
Used .
cript +
DOM.
Suppo
rts
animat
ions,
interac
No tive
client- menus
Intera
side , form
ctivity
interac validat
tivity. ion,
and

Feature HTML DHTML


real-
time
update
s.
Chang
es can
Requir
be
es
seen
reloadi
Page instant
ng the
Reloa ly
page
d withou
to see
t
chang
reloadi
es.
ng the
page.
Chang
ing the
text
color,
size,
Displa
or
ying a
Exam positio
paragr
ple n
aph of
when
text.
a
button
is
clicke
d.
Yes,

Full Form HyperText Markup Language Dynamic HyperText Markup Language


can
Anim create
ation animat
No.
Supp ions
ort using
JavaS
cript.

A standard markup language used A combination of HTML, CSS,


Definition to create the basic structure of web JavaScript, and DOM to create
pages. interactive and dynamic web pages.

Static – content does not change Dynamic – content, style, and structure
Nature
without reloading the page. can change without reloading the page.
Technolog
Only HTML. HTML + CSS + JavaScript + DOM.
y Used

Interactivit Supports animations, interactive menus,


No client-side interactivity.
y form validation, and real-time updates.

Page Requires reloading the page to see Changes can be seen instantly without
Reload changes. reloading the page.
Changing the text color, size, or position
Example Displaying a paragraph of text.
when a button is clicked.
Animation Yes, can create animations using
No.
Support JavaScript.
69
Faculty Name
Thank You!
(shraddhak@[Link])

70
Faculty Name

You might also like