Comprehensive Guide to JavaScript Basics
Comprehensive Guide to JavaScript Basics
1
Faculty Name
Introduction to JavaScript
2
Faculty Name
3
Faculty Name
Key Features of JavaScript
4
Faculty Name
Application of JavaScript
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),
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
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)
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)
12
Faculty Name
Example of variable
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)
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 control the order in which instructions or code blocks are
executed based on conditions or loops.
15
Faculty Name
if Statement
Syntax
if (condition) {
// code to execute if condition is true
}
Example:
16
Faculty Name
If-else statement
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:
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;
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
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.
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:
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).
<button onclick="sayHello()">Click
Me</button>
<script>
function sayHello() {
alert("Hello, welcome to JavaScript!");
}
</script>
</body>
</html>
29
Faculty Name
Object in JavaScript
30
Faculty Name
Create a object in Javascript
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
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
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
Flags are optional modifiers that change how the regular expression
behaves.
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.
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
/^(\+91|0)?[0-9]\d{10}$/
Part Meaning
^ Start
`(+91 0)
[6-9] Starts with 6–9
\d{9} Followed by 9 digits
$ End
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),
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)
47
Faculty Name
Document Object Model
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
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">
Faculty Name
[Link]()
The [Link]() method returns all the
element of specified tag name.
Syntax:
[Link]("name")
Faculty Name
Adding and Deleting Elements
• [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
Faculty Name
Attribute Description
ondblclick Script runs when a mouse double-click
Faculty Name
Form Validation using Javascript
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
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)
60
Faculty Name
Exception Handling in JavaScript
• 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
• 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
}
66
Faculty Name
Example of Javascript
try {
[Link](myVar);
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
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
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