JavaScript
JavaScript
TOPICS: ---
1)What is JavaScript 24) diff b/w textcontent
and innerhtml
2)History 25) Timers
3)How JS runs internally 26) Events
4)Features 27) Math js
5)How to add JSHTML 28) Template literals
6)output & input statements in JS 29) Destructing of array
object
7)JS variables (Rules, keywords) 30) spread operator
8) JS scops 31) Rest parameter
9)Datatypes 32) closures
10)Operators in JS 33) Hosting
11)Functions (types, ways to create) 34) Currying
12)JS objects(ways) 35) synchronous & asynchronous
13)CRUD operations 36) Event loop
14)Nested objects (adding fun, array) 37) promise in js
15)Object methods 38) Fetch
16)JS Array 39) Callback
17)Array methods 40) This keyword
18)Advance Array methods 41) lexical scope
19)JS strings 42) try – catch - finaly
20)string methods
21)conditional stmts
22)loops
23) DOM methods
JavaScript
Scripting
programming lang
Front-end
Backend
1995->Brender Eich
JS
JavaScript
NOTE: live script is re-named into JavaScript just because of
marketing strategy. -->there is no relationship between java and
Jscript
1995mochalive scriptNetscapeBrenden Eich
1996MicrosoftNetscape (Jscript)internet Explorer
{compatibility issues}
1997JS was standardized by ECMA (European computer
manufacturers association) ES1 but we use ES6 (now ES25)
<script> <script>
2)External JS: --
Instead of writing JS code within document, here we make a
separate file for js with .JS extension
[Link] [Link]
</head> </body>
<Doctype html>
<html>
<head>
<title>JavaScript
[Link](“hello)
<body>
</script>
</body>
<script>
[Link](“hi
”) Console
</script> HI
</body>
2)document-write (): --
This method is used to display/print something on the
webpage/document
-
<script> o/p
HI
Document. Write(“hi”)
</script>
3)Window. Alert ()/alert (): --
Used to display / print something in a popup window at top
canter on webpage.
String
always alert instructions will load first
ok
after click on OK then reset to the elements will load
4)Document. getElementById(): --
Used to access and manipulate html elements dynamically using
JS
we want to add content means:--
<h1 id =” heading”>Pentagon</h1> add pentagon space
<p id=” para”></p> add hyd
<script>
Document. getElementById(“para”).text content=” hyd”
</script>
INPUT STATEMENTS: --
PROMPT (): ---Used as input statement in JS, used to take the
value from user
Write a JS prog to add 2 numbers
<script>
A=prompt (“enter value for a”)
A=10
B=20
C=a+ b
[Link](c)
</script>
prompt displays like a popup window at top canter of
webpage
[Link](a)---10
Var a=20-------redeclaration
[Link](a)---------20
A=30-------reinitialization
[Link](a)-------30
2)let: --
let introduced in ES6 version of JS
let having block scope
let variable can be reinitialize but can’t be redeclare
Function demo () {
Let a=10
{
[Link](a)
Let a=10;
A=20 ---------
[Link](a)--- reinitialization
10
[Link](a)
}
Let a=30--------redeclaration
[Link](a)---error
[Link](a)
}
[Link](a)
3)const: ---
introduced in ES6 version of JS
const also a block scop
const variable can’t be redeclared and also reinitialize
Function demo () {
{ Const a=10
[Link](pi) D=30
[Link](pi)
[Link](pi)
VAR LET
CONST
DATATYEPS: -----
JS is a dynamically typed lang
In a time variable declaration, no need to specify the datatype
compiler will understand the datatype of variable based on
value assigned to variable
Type conversion
Name= “anu”-define type of the value
Age=22
Datatypes define the type of value variable is storing
2 categories in datatypes
1)Primitive datatype
2)non-primitive datatype
1)Primitive datatype: --
it is a basic datatype, stored in a stack memory
primitive datatypes store value directly in a memory
primitive datatype holds single value in its variable
pd is immutable
8 datatypes such as: ---Numbers
String
Boolean
Null
Undefined
Symbol
Bigint
2)Non-primitive datatype: --
it is a complex datatype, stored in a heap memory
non primitive datatype stores references/address in a
memory
non primitive datatypes hold multiple values in its variable
it is mutable
object type(only one type )
Such as: -- object
Array
Functions
Date ()
PRIMITIVE DATATYPE: -----
1)NUMBER TYPE: it is a datatype of integers, decimal and
comes under number type
int and float does not support in JS
Ex: let num1=27
[Link](num1)
var num2=49.0067
[Link](num2)
const num3=-12
[Link](num3)
run: right click, integer terminal, type node primitive(filename)
2)String type: A data is enclosed with “or “”is comes under
string
Ex: var name=” anu”
Let city=” Mumbai”
Const age=”22”
[Link](n)
3)Boolean type: any variable which contains value true or false
such type of data comes under Boolean type
Ex: var isplaced=true;
Let ismarried=false
4)Null: declaring a variable and storing null value is called null
datatype
Ex: Let name=null
[Link](name)
5)Undefined datatype: declaring a variable and not assigning
any value is called undefined dt
Ex: var city
[Link](city)
6)Big int datatype: Any value which is greater than 2 to the
power of 53-1 comes under Big int less than it comes under
number type
Big int(12344566788523445678990n)
7)Symbol datatype: Any data which can be created using
symbol ()
Constructor comes under symbol types
NON-PRIMITIVE DATATYPE: -----
Object type: any variable if we are assigning array or object
comes under object type
Ex: var person={
Name: ”anu”
Age:22
Place:”hyd”
}
Console .log(typeof object)-object type
Types of operator: --
In JS we have special operator called type of operator used to
find the datatypes of any variable
Syntax:typeof<variable name>
Ex: 1) var id=59
[Link] (typeof id)number type
2)let name=” anu”
[Link] (typeof name)string type
3) var iscompleted=true
[Link] (typeof is completed)bool type
4)var person= {}
[Link] (typeof person)object
5)let names= []
[Link] (typeof names)object
Operators in JS
JS operators are symbols that are used to perform operations on
operands
Ex: c= a+ b operand
operator
1)Arithmetic operators+, -, *, /, %, ++(incre), --(decre)
2)comparison operators==,===(identical),! =,!==(not
identical), >, >=, <, <=
3)Bitwise operators&(and) *, |(or)+, ^(Xor), ~(not), << (left
shift),>> (right shift),>>> (right shift 0)
4)Logical operators&&(and), ||(or), !(not)
5)Assignment operators=(assign), +=(add assign), -
=,*=, /=, %=
6)Special operators?:(conditional stmt return value based
like if else)
,(comma ope allow multiple exp to be evaluated as single stmt)
Delete (delete property from the object)
In (check if object has the property)
New(create instances), type of(checks type of object)
1)Arithmetic operator: --
Ex: -- let pos=4
Let neg=-4
[Link] (4—4) //8
[Link] (4+-4) //0
[Link] (20/10) //2
[Link] (20%10)//0
Var a=10
[Link](a++)-10
[Link](a--)11
[Link] (1+”3”)13
[Link] (1-“3”)-2
[Link] (1+”1” +2+2+”3”) 11223, (1+1+”3”)23
2)Comparison operators: --compare 2 operands
== loose equality allows type conversion
=== strict equality
Comparison with null, undefined or empty can produce
unexpected results
strings compared with numbers are converted to numbers
always prefer “===” avoid comparison with null or undefined
Ex: -- [Link] (5=="5") //allow type conversion 5 is nbr and
nxt 5 is convert to nbr true
[Link] (true=="true")false
[Link] ("hello"=="1")false
[Link] (null>=0)true
[Link] (null === undefined) //here it not alllow type
conversionfalse
[Link] (5<=5)true
[Link] ([]==0)true
[Link] (13!==13)false
[Link](undefined>=0)false
[Link] ("2">1) //2 string it is converted to nbr so,2>1 true
[Link] ("02">1)true
[Link] (1>"2")false
3)Bitwise operator: --perform operations on operands.
bitwise operator work on 32-bit binary representation of
number
&, |, ^ perform each bit
mainly used in low level tasks like performance flag graphics,
permissions, or binary data handling
Ex: [Link] (5&1)1
[Link] (5|1)5
[Link] (5^1)4
[Link] (5<<1)10
[Link] (5>>1)2
[Link] (-5>>1)-3, (5>>>1)2
4)logical operator: --
Ex: [Link] (10==20 && 20==33)false
[Link] (true && true)true
[Link] (true || true)true
[Link] (false)true
[Link] (!10==20)true
5)Assignment operators: --
let num=5
[Link] (num++)//post increment: value is logged first then
incremented
[Link](num)5
// [Link](++num)6 //pre increment:value is incrementd first
then logged
// let a=12
[Link](a--)--12
[Link](a)
[Link](--a)----11
var num=10
num*=2
[Link](num)-20
num/=2
[Link](num)-10
num%=2
[Link](num)0
num+=2
[Link](num)2
num-=2
[Link](num)-0
6)Special operators: --
let name="anu"
[Link] ("my name is "+name) ----my name is anu
[Link] ("my name is “, name) -----my name is anu
[Link] (50+50) ----100
[Link] (50,50) -------50,50
[Link]("hello")
fun(function(a,b){
let z=a*b
[Link](z)20
})
function fun(callback) {
callback
higher order }
fun(print())
call back fun
fun(add(10,2))
arguments
Ex2: higher(callback) {
Callback ()
}
Higher (function () {
[Link](“hello”)
})
EX3: Parametrized function
Function fun1(callback) {
Callback (10,2)
}
Fun1(function (X, Y) {
Let z=x*y
[Link](z)
Asynchronous fun
Synchronous fun
setTimeout(()=>{ consol
[Link] (“stmt 2”)
{
Ex:let user={
o/p name: 'anu',
age: 22,
isplaced: true,
address: {
city: 'hyd',
name:"anu",
age:22,
isplaced:true,
address:{
city:"hyd",
state:"telangana",
pincode:507160,
area:{
area1:"new road",
doorno:267,
}
}
}
[Link](user)
[Link]([Link])
[Link]([Link])
[Link]([Link])
[Link]="anusha"
[Link]=2672
[Link]([Link])
[Link]([Link])
gender:"female",
city:"hyd",
play:function(){
[Link]([Link],"is dancing")
},
hobbies:["music","dancing","travelling"]
}
var keys=[Link](person)
[Link](keys)
How to retrieve only Values from object?
Syntax: object. Values (object_name)
Ex: var person={ [
name:"anu", 'anu',
22,
age:22,
'female',
gender:"female",
'hyd',
city:"hyd",
[Function: play],
play:function(){
[ 'music', 'dancing', 'travelling' ]
[Link]([Link],"is dancing") ]
},
hobbies:["music","dancing","travelling"]
}
var values=[Link](person)
[Link](values)
gender:"male"
}
let disp=[Link](person)
[Link](disp)
gender:"female"
}
[Link](person)
[Link]([Link]) //allowed2
[Link]="anusha" //changes not allowed
[Link]=5.11 //add not allowed
delete [Link] //delete not allowed
[Link](person)
Array Methods
1)push ()
2)pop ()
3)unshift ()
4)shift ()
5) indexOf ()
6)lastindexOf ()
7)join ()
8)includes ()
9) reverse ()
10)slice ()
11)splice ()
1)Push (): ----
When we need to push any data to an array we use push
method push () always append the data to the end of the array
Ex: let arr=[]
arr. Push (10)
arr. push("anu") o/p: -- [ 10, 'anu', true, 333 ]
arr. push(true)
arr. Push (333)
[Link](arr)
2)Pop (): ---------
When ever we need to remove elements from the array we
use pop ().
pop () removes the element which is present at the last
index of an array
Ex: let arr = ["anu",11, true,81.17]
[Link](arr)
arr. Pop () o/p: -- [ 'anu', 11, true, 81. 17]
[Link](arr) [‘anu’,11, true]
arr. Pop () [‘anu’]
arr. Pop ()
[Link](arr)
3)Unshift (): ---------
When we need to push the data to the beginning of the
array. We use the unshift var arr=[20,"anu",true,20.88]
Ex:// [Link](arr)
// [Link]("anu")
// [Link](arr)
// [Link](19)
// [Link](arr)
Op:------ [ 20, 'anu', true, 20.88 ]
// [ 'anu', 20, 'anu', true, 20.88 ]
// [ 19, 'anu', 20, 'anu', true, 20.88 ]
4)shift (): ---------
To remove an element from the beginning of an array. we
can use shift ()
Ex: var arr= [10,"anu", true,14.55,"chinnu","y"]
// [Link](arr)
// [Link]()
// [Link](arr)
// [Link]()
// [Link]()
// [Link](arr)
o/p:---- [ 10, 'anu', true, 14.55, 'chinnu', 'y' ]
// [ 'anu', true, 14.55, 'chinnu', 'y' ]
// [ 14.55, 'chinnu', 'y' ]
5)indexOf (): -----
this method is used to find the index value of particular
element if the ele is not available inside the array then the
indexOf() will return -1
Ex: var arr = [10,"anu", true,"chinnu",23.33,"y"]
// [Link](arr)
// [Link] (arr. indexOf(true))
// [Link] (arr. indexOf("da"))
o/p:-- [ 10, 'anu', true, 'chinnu', 23.33, 'y' ]
2
-1
6)lastindexOf(): ------
this method is used to find the last index value of particular
element
Ex: var arr=["anu",100,"chinnu",100,true,99,100]
// [Link]([Link](100))
// 6
7)join(): ------
whenever we need to join all the elements inside the array
join() should be used to join() will join all the elements of an
array and return it in the string format
Ex: let arr=[10,"anu",true,45.66,"chinnu","y"]
// [Link]([Link]())
[Link]([Link](''))
[Link] ([Link]('$'))
o/p:--10,anu,true,45.66,chinnu,y
// 10anutrue45.66chinnuy
// 10$anu$true$45.66$chinnu$y
8)includes (): -------
includes () checks weather the data passed to its present
inside the array or not. if its present then it returns true else
it returns false
Ex: var arr=[11,"anu",true,"chinnu",45.67]
// [Link]([Link]("chinnu"))
// [Link]([Link](12))
// true
// false
9)reverse (): -----------
in order to reverse an array we use reverse ()
Ex: var arr=[10,"anu",true,15.9,"chinnu","y"]
// [Link](arr)
// [Link]([Link]())
// [ 10, 'anu', true, 15.9, 'chinnu', 'y' ]
// [ 'y', 'chinnu', 15.9, true, 'anu', 10 ]
10)Slice (): -------------
whenever we need to extract particular elements from
array we can use slice() it will not alter the org array
Syntax: slice(startindex,endindex)
Ex: var arr=[11,"anu",true,"chinnu",34.5]
// [Link]([Link](3))
// [Link]([Link](2,4))
// [Link]([Link](1,4))
// [Link](arr) //it will not alter org array
// [ 'chinnu', 34.5 ]
// [ true, 'chinnu' ]
//[ 'anu', true, 'chinnu' ]
// [ 11, 'anu', true, 'chinnu', 34.5 ]
11)splice (): ----------------
extraction starts at the start index ectracts the length number
of elememts from the array in case splice() it also alters the org
array
Syntax: splice (start, length)
Ex: let num=[1,3,4,5,6]
// [Link]("orginal before splicing"+num)
// let splicedArr=[Link](1,3)
// [Link](splicedArr)
// [Link]("orginal array after splicing"+num)
// orginal before splicing1,3,4,5,6
// [ 5, 6 ]
// orginal array after splicing1,3,4
JavaScript Strings
collection of characters enclosed with in
quotes(single/double) is considered to be string
Var str=”anu” // valid
Var str=anu //invalid
1)String concatenation: ----
combining one or more string together is called as
concatenation inorder to concat 2 strings we should take the
help of + operator
Ex: ar first="anu"
// var last="sha"
// [Link](first+""+last)
// Anusha
How to find the length of a given string?
to find the length of a given string we use length property
Ex:let city =”hyd”
[Link] (city. Length)-3
String Methods
1)charAt()
2)toLowerCase()
3)toUpperCase()
4)slice()
5)substring()
6)replace()
7)replaceAll()
8)trim()
9)concat()
1)chatAt(): -------
if we need to extract a specific character we use charAt()
Ex: var str=” hello”
[Link]([Link](4))
2) toLowerCase(): ------
to convert upper case to lower case
Ex: [Link] ([Link]())
3) toUpperCase(): ------
to convert lower to uppercase
4)slice (): -------
when ever we want to extract substring a string we can use
slice
Syntax: slice (start-index)
Slice (start-index, end -index)
5)substring (): ----------
it is almost similar to slice ()
the difference b/w substring and slice is substring does not
take -ve index
Ex: [Link] (str. Substring (2)) --valid
[Link] (str. Substring (-2)) ---invalid/not valid
6)replace (): --------
we want to replace a particular string with new string we use
replace
Ex: [Link] (str. Replace (“hello”,” hi”)
7)replaceAll():------
replace all are the occurrences with new string we can’t use
replace rather we should use replaceall
Ex: var str=”hello hello world”
[Link]([Link](“hello”,”hi”)) // hi world
8)trim (): ------
to remove the white spaces from the string
Syntax: str. Trim ()
Ex: var str=”hello world”
[Link](str+”welcome”) // hello world welcome
1)trimstart(): ---- To remove starting space
Ex: console. log([Link]()+”welcome”)//hello world welcome
2)trimend(): -----to remove ending space
[Link]([Link]()+”welcome”)// hello worldwelcome
9)concat(): -------
it is used to concat two string
Syn:[Link]([Link](str2))
Ex:let fname=”anu”
Let lname=”sha”
[Link]([Link](name)) //anusha
Break }
Loops
Loops are used to complete repetitive tasks early instead of
manually repeating the task we must take advantage of loops
Types of loops:---
[Link] loop
Syn: for(initialize; condition; Incre/decr){
///stmts }
Ex: for (var i=0;i<10;i++) {
[Link](“the val is “+i)
}
o/p: 1 to 9
[Link] loop
Syn: while(condition) {
…………….}
Ex: var counter=0 o/p: 1 to 9
While(counter<10){
[Link] (“counter value is”+counter)
Counter++
}
[Link] while loop
Syn:do{
//exe the stmts }
While(condition)
Ex: let count=0
do{
[Link](“the count vaue is “+count)
count++
}
While(count<10)
4)For in loop: we can iterate through the object and we can get
the access of all keys of object properties mainly this loop will
access the key of the object
Syn: for(<variable declaration> in <object name>){ }
Ex: var person= {
name:”anu”
age:22
city:”hyd”
}
for(var x in person){
[Link](x) //name,age,city(only keys names)
}
5)for of loop: we can iterate through the array and we can
access of all the elements in an array
Syn:for(variable name of array name){ }
Ex:var arr=[10,34,25,67]
for(var num of arr) {
[Link](num) } o/p: ---10,34,25,67
Note: for loop will not working object
for in loop will working array but it access only index value not
the element
NAN operator
When does NAN occur?
When you perform mathematical operator that does not return a
valid number
Ex: let result-0/0 //NAN
----------------------------------------------------------------------
Head
body
-------------------------------------------------- div
Style script title link
---------------------------
H2 p
Dom manipulation
how to access Dom node (html element)
how to add new html element
how to remove existing html element
how to change content or attribute of html elements
to perform above operation browser is providing us predefined
objects and functions called Dom API
Dom Methods
1)document. Write ()
2)document. Head ()
3)document. body
4)[Link]
5)[Link]
6)document. getElemntbyId ()
7)document. getElementByClassName()
8)document. getElementByTagName()
9)document. getElementByName ()
10) document. querySelector ()
11) document. querySelectorAll ()
12)document. createElement()
13)remove()
14)getAttribute ()
15)setAttribute ()
1)document. Write (): ---------
it helps us write some text directly to the html document
Ex: document. Write (“hi hello”)
2)document. Head (): ------------
it help to acces entrie head section of the html element
Ex: var head = document. head
[Link](head)
3)document. Body: ------------
it helps to access entire body section of the html document
Ex: var body = document. body
[Link](body)
4)[Link]: ------------
it helps to access url address of the html document
Ex: var url=[Link]
[Link](url)
5)document. title: ----------
it helps to access the title of the webpage
Ex: var title = document. Title
[Link](title)
6) document. getElementById(): -------
it is used to find the elements on the webpage based on the id
[Link] will return single element which matches with id
value
Ex: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="one">welcome to js cls</h1>
<p id="two">Lorem ipsum dolor sit amet consectetur
adipisicing elit. </p>
<h3 id="three">Welcome to pentagonspace</h3>
<p id="para"></p>
<script>
let h1ref=[Link]('one') //access the
content
[Link](h1ref)
let pref=[Link]('two')
[Link](pref)
let h3ref=document. getElementById('three')
[Link]="thank you for visting" //change the text
let pararef=document. getElementById('para')
[Link]="hello how r u" //add the contect
</script>
</body>
</html>
11/12/25…… Difference b/w textContent and
innerHTMl
innerHtml: --
if we have any html tags present while using inner html then
inner html property recognizes the html tags
textContent: ---
if we have any html tags present while using textContent will
not recognises and it will print html tags as it is
Ex: </body>
<h1>Welcome to js class</h1>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing
elit.</p>
<h3 id="one"></h3>
<h3 id="two"></h3>
<script>
//difference b/w textcontent and ineerhtml
var h2ref=[Link]('one')
//innerHtml
[Link]="<i>hello</i>"
var
p1ref=[Link]('two')//textContent
[Link]="<i>good mrng</i>"
</script>
</body>
7)document. getElementByClassName(): -----
by using this method we can access html elements
Based on class name
it will return the output in array format
Ex: <body>
<h2>class selector</h2>
<p class="p1">Lorem ipsum dolor sit amet consectetur
adipisicing elit.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.
</p>
<p class="p1">Lorem ipsum dolor sit amet consectetur
adipisicing elit. </p>
<script>
let pref=[Link]('p1')
[Link](pref)
for(var x of pref){
[Link]="red"
[Link]="monospace"
[Link]="xx-larger"
[Link]="cyan"
}
</script>
</body>
8)document. getElementByTagName(): ------
it is used to find the elements using the html tag name and it
will return the o/p in array format
Ex: <body>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<br><br>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<h1>pentagonspace</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing
elit.</p>
<script>
let label=[Link]('label')
[Link](label)
label[1].[Link]="red"
let input=[Link]('input')
[Link](label)
label[1].[Link]="orange"
let pref=[Link]('p')
[Link](pref)
pref[0].[Link]="cursive"
pref[0].[Link]="green"
pref[0].[Link]="x-large"
</script>
</body>
9) document. querySelector (): ----------
it returns the first element in the document , that matches the
specific selectors or group of selectors
if no matches are found then it will return null
Ex: <body>
<h2>pentagonspace</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
<h1>hello</h1>
<h4 class="four">this is heading</h4>
<h4 class="four">this is h4</h4>
<p id="one">Lorem ipsum dolor sit amet consectetur
adipisicing elit.!</p>
<p id="one">Lorem ipsum dolor sit amet, consectetur
adipisicing elit.</p>
<script>
let h1ref=[Link]('h1')
[Link]="blue"
let h4ref=[Link]('.four')
[Link]="green"
let pref=[Link]('#one')
[Link]="5px groove brown"
</script>
10)[Link](): --------
it is used to find the elements on th webpage based on the
name [Link] retuns nodelist it is nothing but arrat of node or
html
Ex: <body>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<br><br>
<label>username</label><input type="text"
name="username">
<label>password</label><input type="text"
name="password">
<h1>pentagonspace</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
<script>
let username=[Link]('username')
[Link](username)
[Link](username[1])
username[1].[Link]="pink"
username[1].[Link]="5px solid red"
let password=[Link]('password')
[Link](password)
password[0].[Link]="yellow"
password[0].[Link]="5px dashed green"
</script>
</body>
11) document. querySelectorAll ():--------
it returns all the elements which matches the query as an
array
12)document. createElement(): -----------
by using this mthd we can create the html elemnets
dynamically
in order add the dynamically created element inside the
document
or webpage we have take the help of append() or
appendChild()
Ex: <body>
<p>Lorem ipsum dolor sit amet consectetur adipisicing
elit.</p>
<div id="one"></div>
<script>
let btn=[Link]('button')
[Link]="click here"
[Link]="blue"
[Link]="white"
[Link]="none"
let body=[Link]
[Link](btn)
let h1ref=[Link]('h1')
[Link]="welcome to class"
[Link](h1ref)
let h2ref=[Link]('h2')
[Link]="hii"
let pref=[Link]('p')
[Link]="hello welcome"
let divref=[Link]('one')
[Link](h2ref)
[Link](pref)
</script>
13)remove (): ---------
by suing this method, we can remove the html elemnets
dynamically for the document
Ex: let href=[Link]('two')
[Link]()
let para=[Link]('three')
para [0]. remove ()
btn. Remove ()
14)getAttribute (): ---------
Ex:
15)setAttribute (): ---the set attribute (name, value)
method is used to set a new attribute or change the attribute
value existing attribute an html element
22/11/25--- TIMERS
when ever we need to delay the execution or we need call
function again and again we use timers
2 types: -----
1)set time out ()accept 2 parameters
1)callback function
2)the time in milliseconds
Ex: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let sayHello=()=>{
alert("hello good morning")
}
setTimeout(sayHello,5000)
</script>
</body>
</html>
Events
All action in javascript we call it as events
Types in console onclick
[Link] action :
Event is nothing but some activity on the webpage
Event consists of two things event listener and event handler
[Link] Listener :
It is used to catch the event occurred on the element
Example:-
[Link],onload,onsubmit,onkeydown,onmouseover,on
mouseout
Onclick :-
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--onclick-->
<button onclick="greet()">Click here</button>
<button onclick="Darkmode()">Dark mode</button>
<button onclick="Generatepara()">generate para</button>
<button onclick="lightmode()">Light mode</button>
<script>
function greet(){
alert("good afternoon")
}
function Darkmode(){
[Link]="black"
}
function Generatepara(){
let pref=[Link]('p')
[Link]="I am dynamically generated para"
[Link](pref)
}
function lightmode(){
[Link]="skyblue"
}
</script>
</body>
</html>
Onchange:-
Onchange events get triggred changing of dropdown option
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select onchange="onDropdownChange(event)">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">Four</option>
<option value="five">five</option>
</select>
<label>Gender</label>
<input type="radio" name="gender" value="female"
onchange="changeGenderOption(event)"">Female
<input type="radio" name="gender" value="male"
onchange="changeGenderOption(event)">Male
<script>
function onDropdownChange(e){
alert("option has been changed "+[Link])
}
function changeGenderOption(e){
alert([Link]+" option changed")
}
</script>
</body>
</html>
Onkeydown :
This events get triggred when we type any on <thead>
keyboard
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" onkeydown="onKeyPress(event)">
<script>
function onKeyPress(e){
[Link]("key pressed"+[Link])
}
</script>
</body>
</html>
Eventcapturing :
The capturing phase is the first phase of event propagation in
the DOM
Event capturing means the event is triggred
First of an outermost or parent element and then it goes to the
innermost or child element
To perform event capturing for the add evnt listener along with
the event type and the callback function
We have to pass athrid argument as true
Syntax :-
[Link](event,function,true);
Or
[Link](event,function,{capturing:true});
Event capturing direction will be from parent to child
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="parent">
<button id="child">Button</button>
</div>
<script>
[Link]("parent").addEventListener("click",fu
nction(){
alert("parent div clicked");
},true)
[Link]("child").addEventListener("click",fu
nction(){
alert("child button clicked");
})
</script>
</body>
</html>
Eventbubbling :
Event bubbling is mechanism in javascript where an event
starts from the deepest target element means the event tiggred
first child element or clicked element and then moves upward to
its parent element
In event bubbing event directions will be from child or parent
Why does event bubbling happens ?
Javascript uses event propagation makes event delegation
possible reduces number of evnt listener in the application
Improve the performance of the application
Ex:- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
<style>
#parent{
border:2px solid black;
padding:20px;
width:20px;
}
#child{
margin:5px;
padding:10px;
background-color: lightblue;
border: none;
cursor:pointer;
}
</style>
</head>
<body>
<div id="parent">
<button id="child">Button</button>
</div>
<script>
[Link]("parent").addEventListener("click",fu
nction(){
alert("prent div clicked");
});
[Link]("child").addEventListener("click",func
tion(){
[Link](); //to stop event bubbling
alert("child button clicked");
})
</script>
</body>
</html>
[Link] handler:
It is function or javascript call
<button onclick=”fn()”>click me</button>
Event is a predefined object in javascript where it contains
All the information related to click event
Math JS
Mathobject :
Math is an in-bulit object In javascrpt which can be used to
perform some specific math operation
Ex:- [Link]([Link])//print value of pi
[Link]([Link](49))//print the square root of numvber
[Link]([Link](9,2))//print the power of number
[Link]([Link](5.6))//round to naearest number
[Link]([Link](2,5))//floor it to nearest integer value
[Link]([Link](23987.87765))//it will print integer value
Template literals
template literals provide an easy way to interpolate
variables and expressions into strings
templates literals use back-ticks (‘ ‘) rather than the quotes (“
“) to define string
Destructing of array or
object
it is a technique in js to unpack properties or elements from
object or array and assigning variables
Ex: object distracting
Old approach new approach
Let
person={ const{name,age,city,gende
r}=person
Name:”anu”, [Link](name)
Age:22 [Link](age)
}
Let name=[Link]
Let age=person. age
[Link](name)
[Link](age)
Array old approach
new approach
Let name=[‘raj’,’nani’,’virat’,’ram’] let[emp1,
emp2, ..rest] =names let[emp1,emp2,…
rest]=names
Let emp1=names[0]
[Link](emp1)//raj
Let emp2=names[1]
[Link](emp2)//nani
Let emp3=names[2]
[Link](rest)//[‘virat’,’ram’]
[Link](emp1)//raj
[Link](emp2)//nani
If we didn’t do unpact
Ex:let[ , , emp3, emp4, emp5 ]=names
[Link](emp4)//ram
Rest parameter
rest parameter allow a function to accept an indefinite nbr of
arguments as an array and also it can applied for array or object
to store elements properties
Syn: function myfun(…args){
[Link](args)
}
Ex: rest with other parameters
function greet(greeting,...names){
for(let name of names){
[Link](`${greeting}, ${name}`)
}
}
greet("hello",'sravs','karthik','abhi','rama')
//example: Rest parameter for array
const num=[1,2,3,4,5,6,7,8,9]
const[num1,num2,...rest]=num
[Link](num1)
[Link](num2)
[Link](rest)
Clousers in JS
it is a technique to access of outer function variable inside
inner function
Or it is function to define function inside another function
A clouser can be defined as a js feature in which the inner
function has access to the outer function variable ,js, every time
a closuer is created with the creation of function
The clouser has three scope claims listed as follows
[Link] to its owm scope
[Link] to the variable of the outer function
[Link] to the global variable
Syn: function [Link]() {
Function function_name() {
}
Return function name
}
Ex: //Access the variable of its own scope
function outer(){
[Link]("i am outer function")
function inner(){
[Link]("i am inner function")
let city="bangalore"
[Link](city)
}
return inner
}
let res=outer()
res()
//Access the variable of outer function inside inner
function
function fun1(){
[Link](" i am outer function")
var name="virat"
return function fun2(){
[Link](" i am inner function")
[Link](name)
}
}
let result=fun1()
result()
//Access global function
var age=30
function person(){
[Link](" i am outer function")
return function fun2(){
[Link](" i am inner function")
[Link](age)
}
}
let details=person()
details()
24/12/25---- Hosting
hoisting is js default behaviour of moving variable and
function declarations to the top of their scope before
execution
How it will work
works with var (hoisted but undefined) and function
declaration (hosting with definition)
let and const are hoisted but remains in the temporal dead
zone (TDZ)
Both variables and functions are hoisted but different behave
How it works internally?
When js engine starts
[Link] phase (memory creation phase)
it scans the code
it creates memory space for variables and function
variable declarations are set to undefined
function declaration is fully hoisted (entire function
declaration)
[Link] phase
code runs line by line
Hoisting for var
Ex: [Link](a) //undefined
Var a=10
[Link](a) //10
Ex: var b // hoisting
[Link](b) //undefined
b=100
[Link](b) //100
Hoisting for let and const
Ex: Let b=20
[Link](b) //20
[Link](c) //reference error
Let c=200
let and const are also hoisted but kept in (TDZ) temporal dead
zone a period where the variable exisits bit is not accessible until
its initialized
Ex: let d; //hoisted
Hoisting for function
Ex: greet () //gm
Function greet () {
[Link] (“gm”)
}
entire function greet is hoisted so you can call it before
declaration
Note: only function declaration are fully hoisted function
expression and arrow functions are behaved like variables
Ex: say Hello () //type error
Var say Hello= () => {
[Link](“hello”)
}
say Hello() // hello
currying in JS
currying is a functional programming technique where a
function with multiple arguments is transformed into a sequence
of functions, each taking a single argument at time.
Or
currying breaks down a function that takes multiple arguments
into a series of functions that each take a single argument.
Example of a normal function
Ex: Function add(a,b,c) {
Return a+b+c;
}
[Link] (add (2,3,4)); //output:9
Example of a curried function
Ex: Function add(a) {
Return function (b) {
Return function (c) {
Return a + b+ c
}
}
}
[Link] (add (10)(20)(30)) //60
Benefits of currying:
[Link]: you can create specialized functions by fixing
some arguments.
Ex: const multiply=a=>b=>a*b
Const double=multiply (2)
Const triple=multiply (3)
[Link] (double (5))//10
[Link] (triple (5))//15
[Link] Application: you can create new functions by pre-
filling
Ex: const greet = greeting => name => `${greeting}, $
{name} !`;
Const sayHello =greet(“hello”);
[Link](sayHello(“alice”)); //” hello, Alice!”
Ex: const discount = rate => price => price – (price * rate);
Const tenpercentDiscount=discount (0.10);
[Link] (tenpercentDiscount (100)); //90
[Link] (tenpercentDiscount(200)); //180
[Link] Readability: functions can be more readable and
easier to understand.
Currying v/s normal function
Normal function
all arguments are passed at once
less reusability
Harder partial use
Currying function
arguments are passed one at a time
more reusability
easier partial use
Resolve ()
reject ()
then()
catch()
Creating a promise
creating a promise using promise constructor take a function
with two parameter resolve and reject
here the promise will be either be resolved or oi will be
rejected
Ex: let promdemo=new Promise((resolve,reject)=>{
let condition=true
if(condition){
resolve("promise fullfilled")
}
else{
reject("promise rejected")
}
})//fetch() ---used to fetch the data and call api’s
Handling promise result
To handle the promises we use 2 methods
1)fulfilled---then () method to handle the promise result
2)rejected-catch () if any errors occurs, then we use .catch
Ex:promise chaining
[Link](res)=>{
[Link](result)
})
.catch((error)=>{
[Link](error)
})
Promise—the better way
Creating a promise
const mypromise=new Promise((resolve,reject) =>{
const success=true;
if(success){
resolve("operation successful");
} else{
reject("opeation failed!");
}
});
//using a promise
[Link](result=>{
[Link](result);
})
.catch(error=>{
[Link](error)
});
Fetch
fetch is a method which works internally as a promise
fetch method is used to make a n/w request or to call a api in
js
Fetch will return a promise in js
Ex: fetch('[Link] //make api call
.then((res)=>[Link]()) //return promise fullfill
.then((jsondata)=>{
[Link](jsondata)
})//fullfill
.catch((error)=>{
[Link](error+"promise failed")
})//rejected
Callback hell
callback hell happens in js when you have multiple nested
callbacks inside asynchronous function like settimeout, api calls
etc
it makes code harder to read and hard to maintain
it old pattern to handle asynchronous function in new pattern
we are using promises async/await method
Ex: [Link]("customer enters restaurent")
setTimeout(()=>{
[Link]("waiter takes order")
setTimeout(()=>{
[Link]("chief starts cooking")
setTimeout(()=>{
[Link]("food is ready")
setTimeout(()=>{
[Link]("waiter serves food")
setTimeout(()=>{
[Link]("customer starts eating")
setTimeout(()=>{
[Link]("customer pays the bill")
},1000)
},1000)
},1000)
},1000)
},1000)
},1000)
function step(message,time){
return new Promise((resolve)=>{
setTimeout(()=>{
[Link](message)
resolve()
},time)
})
}
//example using promises
function step(message,time){
return new Promise(resolve)=>{
setTimeout(() => {
[Link](message)
resolve()
}, time);
}
}
step("customer enters resturant",1000)
.then(()=>step("waiter takes order",1000))
.then(()=>step("chief starts cooking",1000))
.then(()=>step("food is ready",1000))
.then(()=>step("waiter servers food",1000))
.then(()=>step("customer starts eating",1000))
.then(()=>step("customer pays the bill",1000))
.catch(error)=>console. error("error",error)
Scope in js
Scope refers to the accessibility
scope can be used for functions and variables
There are 2 scopes in js
1, global scope
2, function scope
1)global scope:
if any function or variables or class or not defined inside
the block ({}) then they are said to be in global scope
Ex: var city=” Mysore” //global scope
Function fun1() {
[Link](city)
}
Function fun2() {
[Link](city)
}
Function fun3() {
[Link](city)
}
Fun1()
Fun2()
Fun3()
2)function scope: ----
anything which is defined inside the function scope those
things we can access only inside the function scope
Ex: function f1() {
Var name= ” anu”
Function fn () {
[Link](name)
[Link] (“fn is called”)
}
[Link](name)
Return fn
}
[Link](name) //error
F1()
Fn() //error
Lexical scope
lexical scope means that scope is determined by where
variables and blocks are written in the code means inner
scopes can access variables from their outer scope
Ex: function outer () {
Let a=10
Function inner () {
[Link](a) //can access a bcz of lexical scope
}
Inner()
}
Outer()
Try---catch---finally
whenever we feel some part of code may cause problems,
we must enclose the part of code with in the try.
so if any problems occur try is designed in such a way that
is throws the exception object outside which later will be caught
by the catch()
by using try-catch syntax we can avoid our programs getting
terminated abruptly
Syntax: try {
//code
}
catch(err) {
//to catch the error expression
}
Finally: ---------
finally block will get executed irrespective of exceptions
Ex: try {
Var num=20;
Fname:”anu”
[Link](‘num’+num) or (‘num’ / num)
[Link](err)
}
Finally {
[Link] (“finally executed”)
}
//manually throwing errors
Ex: try {
Var num=20;
Fname: (”anu”)
Throw new error (“product id not found”)
}
Catch(err) {
[Link](err)
}
Finally {
[Link] (“finally executed”)
}