.
Tavascyipt can change HTML content-<(p>
click Me} <|button>
Scuious)
What can TavaScvibt do?
Tavaswipt can change HTML Content
Click
1)
onclick button then the content will change
Hello Tavasevipt !
Java suvibt Can change HTML Attyibvte Valves
In tnis example Js Changes the value OF the Syc (Source) aHvibutes
OF an tag
gimg id="myTmage" sve TBUIbOFE-gif” style= "Wwidt)
oopx"/>
Abution onclick
"document. get Element Byfd CmyTmage’>. svc =' bulbs sie
‘> Turn OFF the light <[ button >
{Torn oF¢}
Created By Karnal Navan Upadinynyi
i
TavaScvibt can change HTML Style (css)
document gerElementById ("demo’). style. Fontsize = "35 px";
Ex- kamal — Kamat
JavaScribt Can Hide HTML Elements
document. get Elem entByfd ("demo"). style display= "none";
Javagcyipt Can Show HTML Elements,
document. get Element By Td("demo").style disblay = "6
Did you Know 2
* JavaScript and Java aye Completely diggevent languages -
lock";
* Tavascyibt was invented By Brendan Eick in 1995 and
became an EcmaA Standayd in 1947.
* ECMA-262 is the official Mame oF the standard
ECMAScript is the o¢¢eicial name of tne language:
Java Styipt wheve To
4. dsevibt> Tag
\
2. ov
3. Tavasevibt in Body
4. Extevnal Tavascyipt
Cyeate Extevnak File
MySevipt-Ts
ovcbody>
K
eeti ge eee
Java Scvipt Output
Vavascyipt Display Possibilities
1 boviting Into an HTML element, using innevyHTML
2 Writing into the HTML output Using document writed)
3. writing into an alevt Box, us ng dlevt()
4. writing into the byowsey console, uSing console .log()
4. Using TnneyHTML
document. getElement ById (’demo").innevHTML= S46; 11
2. Using document.write dc) > Foy testing buy pose
document. wvite (S+6); 14
Note: Using document -wvite() @etey an HTML document is
loaded, will delete ait existing HTML:
Example: Print this Page <|button>JavaSevipt Vaviables
4. Using vay
using Let
2
3. Using const
4
=
4 Ways to Declaye a JavaScvipt vaviables -
-
-
ba
using nothing
Vayiables - vavidables ave containers ¢oY Storing data
Vay x= 5)
When to Use JavaScript vay 7
Always declaye JavaSwipt Vvaviables with vay, let,ov const
The vay Keyword is used in all Tavascyipt code From 199512015.
The Let and Const Keywords weye added to Javascript in 2016.
Te you wart youy code to yun in Oldey byowsey, you must
use vay-
When to use Javascribt const 7
“If you want 4 genevat rule: always declave vayiable with cons
* I€ you think the vdue of the varidble can changé, use Let
Exampie: const pyicet = S;
const pyicea = 6;
let total = pyicer + pyice2;
Javascyipt Identifievs
All Javascvibt vayiables must be identified with unique names
These unique names ave called identifievs.
Rules Fov creating vayiable
1. Names car contain tettev, digits, undevcos and dollay Signs
2, Names must begin usith letter
BNames can dlso begin with $-
4.Names ave case Sensitive (yand Y ave diereyent variables)
5.Resevved words can't be used ab a name-Tavascvibt Let
The Let Keyword was Intvoduced in £S6 (2015)
Vaviables defined with let can’t be Redeciaved
Vaviales derined with let must be Declared before use
vayiables defined with let have Block scope
s
>
<=
=
~
=
~—
=> Camnot be Redeciaved
= vayiables degined with let cannot be vedeciaved
=> Ex- tet x = "kamal";
— et x= 63
a
ae
=
—
i
Syntax Ervoy + °x' has alveady been declaved
Block Scope
Before £s6(2015), TavaScvibt has only Mlobak Scobe and
Function Scope-
Es6 intyoduced two important new Javascyipt Keyenords: let.const
These two keywords provide Blocw Scope in Javascyipt
Vayiables deciaved inside a 41 block cannot be accessed From
outside the block
Exampie
i
let x=
5
= X cant be used Here
vaviabies declared with the vay keyword Can NoT have block supe
Example
2
det x=2;
3
X can be used Hever JavascviPt Const
* The const keyword was intvoduced in Esé(2015)
* Vayiables defined With const can’t be vedeciaved
| * vaviables defined with const cant be reassigned
* vayiables defined with const have Block Scope
| Can't be Reassigned
Ex: const prs 3-(eH15;
PI= 314; @ This opi)! give an evyov
Must be assigned
Const Pr= 3.14; - covvect
const PI)
Pre 314
> Sncovyect
When to Use Javascript Const ?
Use const When you deciave
=A new Avvay
+ A new Object
*A new Function
* A new Regexb
Block Scope
Peclaving aq vaviable with const is similay to let
When it comes to Block Spe:
Example-
const xX = 40;
t
Const x= 2;
3
4 Heve x is Ao;
PEFILPPIPPISPSLSLPLIIILIFILIRIOMRA@S Oe~
~
~
~
~
=
~
=
=~
Javascvipt Opevatoy
Tybes of Tavascvibt Opevatoys
1. Avithme tic Opevatoys (+,-) 44, L%e,++,
2. Assignment Opera tors (= +=
3. Combavison opeya tors (:
4
Logical opevatovs (&&, 11,1)
5 Conditional opevators (
Tybe Obevatovs (typeoe, instanceoe)
Adding Styings And Numbeys
Example
let X = S45;
let y = e445:
yi
let Z= “Hello” +5;
Ovtpot
1o
ss
HeliosTJavascvipt Avitnmetic
let x = 100+50;
Opevatovs And Opevands
be {00,50
4. Addition (+)islet X='5> lety= 6; leFz= x+y;
2. Subtvaction (-): let x=5; let y= 6; Ietz= x-y;
$. Multiplication (#): let x=s; leky= 6; lep2=x ky;
4. Division (/): lerx=s; lety= 6; let z= XIY;
5. Rermmaindev(%): let x=5; lety=6; let z= x%o¥;
&- Incvementing (r+): let x=5; x44; let 2= x;
7. Decvementing(—-): let X=S; x--; let z= x}
8
Exponentiation (*x): let x=S; let z= xxx2; 3 52 = 25
X¥*yY produces the Same YesuIt as Math. pov (x,y)
let x= 5;
let 2 = Math.pow (x,2);
Tayascyi pt Assignment
4 TavaScript Assignment Opevakoys
OPpevatoy Example same a
= = Key
+ aaa eels
= Xeey xX =x-y
Cie x4 y x= xty
= x/=y SeXy
‘he x %o=y Xa KRY
Hee id = xyae ee ee ae eee ee
TavaSwibt DataTybes
Theve ave two types of data Types in Javascript
A. Pvimitive data type
2. Non- Pyimitive data type
4. Pyimitive data type
* Stving - let name = “kamal”;
* Number- let x= 12;
* Boolean- let x=5; lety=s; lerz=
Yj veturns Tyve or False
* Undefined- let cav; vatoe Is Undefined, tybe is undetined
* NON= let cays He yp The value iS "", the typeof is "Stving”
2. Non- Pyimitive data type
* Object - consi peyson = iFName :*kamak”, LastName: "UPadhyay"§;
*Away- const cays = C"BMW", “Volvo”, “Saab!
The typeof opevatov
The typeof opevatoy vetuyns the type oF a vaviable-
let a= 12;
console. log (typeor (ad);
Numbey:JavaSevipt Functions
A Tavasevibt Function is a block of code designed to
Pevform a payticulay task
A Javascvibt Function 1s executed When Something calls it
Function syntax
Function mame ( Pavametey4, pavameter2, payameter3) §
Meode
Fonction veturn
when Is Yeaches a yeturn statement, tne Func will Stop executing
Exampie
Function myFunction Carb) ¢
veturn a#b;
4
console.log(myFunction (3,4));
Why Fonctions 2
You can yeuse code: Define tne code once, and use tt many Himes
You Can use the same code many times with digreyent
avguments, to Produce dig¢eevent result
Example: Function tocelsius(Fahvenheit) §
verurn (s/9) #(Fanvenheit-32);
3
document.getElementByld (“demo”) .jnnevHtML = recelstus (71)
as
-SaReRPPRrPDSeBRre_SIPSesaefpnpeP QaeoeaeaeHRaehoaonmnnennnnin.~ TFS SSETSTSSOSSSESVVV VEO eV
Javascript Objects
Real Lige objects, Properties, and methods
Object
“Cay > metnods
Cay.stavt()
‘ cay. dvive (
Propey ties
cayname = Flat
Cay.coloy = unite
Pvopevties > same but values diffey From cay to Ca¥
methods » same but the methods ave perfovmed at airfevent time-
const cay = {
tybe: "Fiat",
model: "S00";
cole: “white”
a
Accessing object pyopevties
ObjectName.pyopevtyname
ov
ObjectName (“pyobevtyName"IJavaScvipt Events
Common HTML Events
1. onchange
2. onclick
. on Mouseovey
on keydown
3
4. ON Mouse ovt
Ls
6. onload
Example
4 pocTyPe Nemi>
ébutton onclicK="document. getElement®yTd (Udemo!). inner
HIML= Dote()”> The Time is?
Zp id="demo"> Z| P>
<}body>
Output pn
ae
Tha Olt 14 2023 21:56:28 @MT +0530 (India standard Time)eee ee aie ae a ee ee
Javasevibt stving
Javasevipt Stvings ave Foy stoying and manipulating, Text
let name = “Kamat”;
Stving Length
let text = "Kamal";
let length= text length;
console. log (length); //S
TavaScyipt Stings as Object
let x = "Kamat"; — stving
er y= new stving("Karnad”): > olojeck
Don't cyeate Stving object
The new kKeywovd complicate tne code and slovw2 down
execution Epeed
Sting object can pyoduce unexpected yesult
h
"
®
eevee let a = 105
let b= ‘40; let. b= 14075
tek C= 40;
Console-lo4 (a
b); > False
Hovtpur te
consele-log (
Console. log (a=
=0)3; 4 twe
=Kcheck datatyp & check datatype then
give output:Tavascvipt Methods (Stving).
Extracting Stving Pavts
Theve ave 3 methods Fov extvacting 4 part oF astving
‘1. Slice (Stayt, end)
2. substying(stavt,end)
3. Substy (stavt, length)
4, Tavasevibt String slice ©
Siicet) extvacts a bayt of a stving and yeérurns the extygcted
payt in qa new string
Ex- let sty = "Apple, Banana, Kiwi”:
let payt = stvslice(7,la); — Banang
Slice ovt a povtion o¢ a stving From positien 7 to position 13
3 Not includes)
2. JavaSevibt Stving substring)
Substving © is similav to slice ©)
The diggevence is tnat stuvt and end valves less than o ave
treated as 0 in substyingO
3. JavaScript Stying Substy ()
SubStv() is similav to slice C)-
Thé dipgevennce is that the second pavametey Specifies the
length o€ the extvacted payt
let stv = "Apple ,Banana , kiwi")
fet pavt = “sty. substy (7,6);
Replacing String content
The veplacec) methods yeplaces a Specified value with another value
let t¥t ="“Please visit MicvosoFt”,
let newtxt = txt, veplace C'Micvosoet” “kamat");
Converting 4 Uppey And Loweycase
toUppevcase ()
et txt4 = "Helo world";
les txt2 = txtatouppevcase ():
HELLO WoRLD.toLowevtase()
let texta = "Hello Wovid”
let text2 = texti.tolowevcase()
helio Woyld
Stving concurs
let fextd = "Hetio”
et text2 = "wWovid";
let text3 = textt. concatin, text2 5
Tavascvipt stving timo
fexta tvim ();
Tavascvipt stving tvimstart (°
texts. trim stayi O;
davasevipt stving timend Oo
texta.trimend ©
JavaScript Stving Paading
Padstavt ty
let tet = "5%
let padded = text.padstuyt(4,"x"); > xxxs
Pade dc)
+ext padiend (4,"0") > S000
Extvacting String Chavacteys
1. Chavat (position)
2. ChayCodeAt (position)
3. Pyobeyty acesst3
1. Chay At 0)
let text ="HELLO WORLD”;
let chay = text.chavAt(o);
H
2. ChoyCode At ©) > methods yeturn the Unicode OF tne Chayactey at
G specified index in a Stving. Method veturns a UTF-16 Code
text cnavCodeAt (0) > 72
3. PrOpevty Awess 4 Converting Siving to an Ayvay
let chav = tertCa) > H SpliEO)Javascvipt stving Seavch
Javascvibt Seavch Methods
a Stving indexor() > index oF the Fivst occurence
let Stv= "Please yocate wheve ‘locate 'accuvs |";
Sty. imdexor (locate): > 7
2, Stving lastIndexOF (> vetuyns the index oF last occuvence
Sty. lastindexoF ("locate"); 9 24
3. String Seavch ()> veturns the position of tne match and
Seayches a stving fov a Speci¢ied value:
Stv.seavch (“locate”); — 7 .
Did You Know (Notice ) ?
Imdexord) and seaych 0), ave equal
The two methods ave NoT equal
Seaych() > can't take asecond stavt position avgument
indexof() > can't take pousevful seavth valve (veg: Oxpression)
4. String match) - match metned seavches a stving Foy a
Matin against a stving ang yetuyns the matches, as an Aray
object-
lex text
The vain im SPAIN stays mainly tn the plain",
teyt. Match ("ain ;+ | ain
tev makn (Vain!) ; 9 Lain sean”
tert math Vainiay; > 3 Cain’, ain! ging
fe-match Vain igi) —r4 Lain ain cin,ain) > cuse-insensitive seavch
5. Stving marchanc
Const iteyatoy = text-matchAll(”cats")
. Stving includes) ~ returns tvwe
let txt = "Hello World, welcome to the Universe"
teri.includes ("World"); + True
+ext-fincludes ("world” 2); > False
Syntax:- stving. incdodes (seavch Valve, Stave)
Requived canalwe @ ef © 4. Oo 2 Oe 20 6 oe ee
7 Stving StaytswithO — retorin tye and Faise
let txt = "Hello world, welcome to the Universe-"s
typ Stavtwith ("Hello") > True
Syntax:- Stving.stavtswith(seaycnvalv é, Stayt);
‘ obtionag
¢
Requived
8. Siving endswitn - veturn tvue amd Gols e
let tet = {Hello world”;
tyetendswith world") 57? Tue
Syntax“ Stving-endswit (seavonvalve, end ) >
J \ optionod
Requivedoll
JavaScript Template Litevais
4. Intevpolation
Sitar
Vaviable substitutions
let Frame = "Kamat";
let LName = "Upadhyay";
let txt = "Welcome ${rwamed, $name}
2. Back-Ties Syntax
Template Liteyous vse back-ticks (*%) yatney than the
quotes (") to define a string:
a * ovld’
Con Epis tory let text = ‘Hello Wor
tensolelog (rext) I Hello world
a Ovotes Inside Stvings
With temblake Ifrevals “
let text= ‘tam good" oyOOP RRR URE ee
Tavagevist Numbers
Adding Numbers and Stings
let x= 65 | \er ne”
lery= (0 | eryee
Pe ig lire xty.« bt
et x= 10
eh y = "20"
yer z= xayj > 1020
Numeric Stving
\ek x= "109",
let «= 1100")
ler y= M0 let y= "4"
lee z= KY; 710 tet z= HY? 100
Tet x= M00" jet x= "100";
ler y= "10" \ery = "10%
er Tiesd au yea Ncies tz EU YS VON?
NAN - Not a Numbey
let x = t00/"Appie >» NAN
iswanty); — tvue
yet x= Naw;
ler y= 57
jer z= xay — NANJavascvipt Numbey Methods
The tostving() Method
returns a hombey as a Stving
let x= 123;
x. €ostving > 123
The toExponenticl() Method
veturns string, with & number rounded and written using EN
9656;
X-TOEXponentiol(a); > a-6scer6
let
The toFixed Method
veturns @ Stving, with the umber written with a specified oF decinas
let x= 9.656;
x. toFIxed (0); + Io
DADDADDADOADGDH«ranoe«a
Rrorixed@); > 466 > torixed(2) is percent Fov wovtingamoney .
XtOF ined Gi g.e5¢0
The topPyvecision(y mernod
verorns a Stving, with tne numbey writen with a specicied lengtn
Ver x = g.656-
X- toPyecision (); > 9-656
x. FoPvedision (2); 5 9-7
X. roPvecision(4); 5 465600
The valueOr() wietned
yeturnna. as numbev
let x = (23;
¥.ValUeOF () 5
PPPPLOPOOD
Convevting Vaviabjes to Numbers
1. The Numbev() methods
lek a= 12;
let b= Numbev(a)
fonsole. log (bypeog (b) )
Number.
«
«
«
=
&
se
&
=
4eee ee eee ~«
2. The payseintc) Method
pavse a stving and vetuyns a whole Numbev
let a=;
let b= pavSe int (a);
console-tog (ryPe oe (b)).
3. Te payseFloat () Metnod
Vek a =12;
let b= pavse Float (9);
console.logCty pede (b) 2:JavaSuvibt Avvays
creating an Avray
Const arvay-name =Citema, item2,...J;
Accessing Avvay Elements
Const cays = C"saay' ‘volvo’, "eMw)"y,
let Cavs cavs(o] + saab
changing an Avyay Elements
Caysfo} = “opel”;
Access the Full Avvay
Const cays = ("aab","volvo", "Bmw" J
Consele.iog (cavs)
Access the Last Avvay Element
let cays = cay [eav.tengry 4) > Bmw
Looping Away Elements
const Fwits = ["Banana’, "orange “appie’
let Elen =
mango”) ;
Fruits.en gtn
leh text = "UU>”
a Banana ovange A pie wane
Fov(1et ic 0; ic tien; ing
text
3
Adding Away Elements
+ Fyvittid ;
PUSh () method
Const Fyits = C" Banana”, “ovange’, Apple’, "Mango";
let & = Fwits. push (’Lemon");
Console.iog (F) 35
Console. 12g (Fyuits) > G) (Banana ,"ovemgt"; appre’, Mango”, “Lew D
The Difference Beiween Ayvays And Objects
> Aways use numbered indexes — stving( text)
> Objects vse named indexes — (mumbev)
_— lh. Fh oe om i i em bo ef hb db bd ODHow to Recognize an Away
A common question is. How do I know iF a variable is an away
The problem is that the TavaScribt opevutoy typeor vejums “Object!
Const Fruits = L"Banana’, "ovange”, "Able" J
let type = tybeor Fruits
Console. log (ty Pe) > Object
The typeof opevatoy returns object because d TS away is anobjes
Solution 4
To solve this pyoblem ECMASibts(@003) derined anew method
Ayvay. is Avvay ©)
Avvay. isAvvay (Fyuits) > tue
Solution 2:
The instunceoe opevatov returns tye (Ff an object is cveated
by a given canstwetor
Fvvits instanceof Avvay > TyeTovaScvip} Ayvay Methods
Converting Avvay +o stvings
fostvingd Converts an away to a stvingoF (cormma sepavted)
ayvay object value
Const Fvvits = ["Banana”, "Ovange", "Abbie";
let Convey = Fyoits. tostving ()
Console. log (tybeor (convevt)) > sting
Console. log (Convert) > Banana, ovange, Abple
The Joined) methods also joins ati avvay elements into a string
Ty benaves Just like tosiving(), bur im addition you can specicy
tne Sepayatov-
tet join = Fyuits-joln("*") > Banana x Ovange * Apple.
Popping And Pushing
Tavascvipt Avvay Pop)
The popO metnods vemoves tne last element From anavray
const FWwits = C"Banana", "ovang”, "Mango'd ;
Console.log (eyits.PobO) > Mee Mango
console. 19g ( Evits) > @) [’Banana’, ‘ovang']
Javascvipr Away Pusht)
The push) methods add new elements to ay avvay (at the end)
const Fruits =
"8 anand’, “ovange”, "Mango";
Comsole.log (Fyvits. Push (“AbpIE”) ;
console. log CFwits)
4
) C’Bananai, ovange’, ‘mango, Apple!)
es eh RARE KEK HHHHGRE GS LOBR BBR Ae BGeeeenvr2teooo 888888 tte 8 ooo OO
Shieting Elements
Javascvipt Avvay sniet
Shift methods vemoves the Fivst avvay element and "Shirts
all othey elements to a lowey index
const Fvuits = C”Banana’, "ovange”
pple"]
consolelog (Fvuits.shiet() > Banana
console-log (Fruits) > @) L'ovange’,‘Abble'J
Javasyipt Avvay Unshiet ©
Unshiet ( methods add a new element toan ayvay (at the begini)
Semon!
Console.log (Fvuits-unshir O) > 4
Console.og ( Evuits) > @ L'Lemon’, ‘Banana’, ‘ovange’, Able’ 7
Tavascyipt Avvay Splice
Splice) Methads can be used to ddd a Mew items to anavray
const Eywits = E"Banana’, "ovange", “Abbie”, "Mango"];
(et add = Fyvits.splice Leman”, "Kiwi" > [Banana ovange
d
derenEne dering hows many ‘TEM, ‘Abe,|Mowyi]
position wheye element snovid be
newelements removed:
Shovid be added
let add = Ewits.splice 2,2, "Lemon's ‘kiwi")
[Appie', mangé]—> removed
(Banand, evan ge’, ‘Lemon’, Kiwi’) — new Arvay-
Using splice © te Remove Elements
Fruits. splice (0.4)
Banana, ovange, Abbie, Mango — Ovigina? Arvay
Ovange, Apple, Mango- new Avvay.a
Javascvibt Sovting Avyvays
Sorting an avray
The sSovt() metnods sovts an avvay alphabetically
Const Fits = C*8anana®, “ovange", “Apple®, “Mango")
Console. log (Frvits.sovtt));
Apple, Bananc, Mango, orange
Reversing an Away
The yeverse © methods veverse the element in anavvay
Console. log (Fvuits-veverset) )
ovange, Mango, Banana, Abbie
Numeyvic Sovt
By derauit, the sovt© Function Sovts values as stvings
P This works well’ Foy stvings (“Apple” comes befove “Banana’)
> Howevev, if numbers aye Sovted as Stving,%25" is biggev
than “100% because “2” is biggev than "4":
? Because OF this, the SovtO methods will produce incowvect
result when Soyting numbey:
7 You can Eix this by. pvoviding a compave Function
Const points = (40,100 /4,5,25, 10]
let G= points SovE(Functon(a.b) <
Veturn a-b) 4)
Co osole Cl) eat(6) Gad cfr » £0, loo]
Away descending
Poin ty .Sovt (Function (az) §
vetuy (6 ~ 4 4)
loo 40,25, (o,s,4
pppoe eEeRKKLPCPPPPPPPIPPP@PPPaepvesreaereraerzvrititEE EEEESSEZSESFESSEEEELHFSOSHGOOOGOOVOHUNUNN””
Sorting An Ayvay in Random dvdev
Const points = £40, 100,46, 25,10];
let Sovt = points-covt (Fun cHon() {. vetuyn 9:5 =m aby. vandor\) 3);
Console-toy (sovt); (6) Las, 40, 19, S, 10/4)
Find the Highest (ov lowest) Avvay value
Console.tog (paints (0]) + contains tne lowest valve
console. (oq (points (points. length -1]) + contains the niignest val ve
Using Math max on an Avay
vray
You can use Matnimax abbly te Find the highest, numbey In an &
eundion myAwMax (avy) &
verorn Math-max-aPply (mul avy)
3
Consoje-tog( my AvyMax (Points)? > 100
Using matnmind en an AVYAY
Oe rn ey, aca) ae area aeJavasevipt Avay Stevation
Away itevation methods opevate on every avvdy item
TavaSevipt Avvay FovEach (>
The foveacn’) methods calls a Function (a calleack fundion)
once fov eath ayvay element
const numbevs = £40/100/4/5, 28,40}
yey Fext = 95
numbers. foveach (myFunction);
function my Function (value, index ,avvay) &
text t= value
3
console.1og (ext) 3 49/100/15,25, 10
Ln 4g aa ness D asa A IhSm FT SP SSSSSSOOSHSSSFZOVCOGOCOOCSSSSSSL
Tavasevipt Away
The MmabO memods create a new aay by performing &
Function on each avvay @lernent
The map) memods doesn't execute tne Furic y ave
elements without valve
The mapo memods doesn't uange the oviginas array
Example :-
const nums © (45,4, 4, 16/25]
const num2 = Numi map (myFundion)
Function myFuncton valve, index, avvay)t
vetrn value 42;
3
Consoie.1og (num2) -» 40, 8,18, 32,50
Tavoscvip Away Filtev()
4. The Filteviy methods cveate a neu avvay with avyay eleMen
tak pass a test
Example -
const numi= £45,4,5/46/25;
Const ovev4g = numd. iltey (myFunction)
Eunction myFunition (valve , index ,avvay) &
verum value > 18;
5
console.loy(ovevia) 9 45,25yeturn total + valve ;
3
console-'og (sum) > 33°
Javascvipt Away veduceRignt oO
Tavasevibt Avvay Reduce O
4. The yeduce() metnods yuns 4 function on eacn avyay
element to pyoduce (veduce it to.) a single valve
2. The yveduce() methods wovks FyYomM \eet-to vignt in tne
ayyay. see Also yeduceRignt O
The yedueet) metnods doesn't reduce te Cy aay
const numbevs = £45,4,9, 16,2535
let sum = numbeys veduce (my Function) ;
Function myFunction Goral, value, inde away) &
4. The veduceRignt) methods vuns 4 function on-eacn ayvay |
element to produce (veduce iF to) a Single valve e
2. The veduceRigntO works Fyom vight-to-leet fin the avvay: C
m Be «
The veduceRignt ) methods doesy'+ vedule te oviginal away. ¢
m ‘
ler sum = numbevs. veduceRight (myFundi on) ; ;
eutput > 99 |
TavaScvipt Avvay evevy O
4. The evevy() methods checks ig all avvay value bass a fest
let Gliovevig = numbers evevy (myFunction)
Fundien — valve> is
Ovsput - FalseTavaSevipt Avyay some.
A The same) meinod checks iF some dyvay values Pass 4 fresh
let someovevis = numbevs.some(myrunttion)
veruyn value > 18
eutpar- fue
Javascvipt avvay indexor 0
4. The indexog() methods searches an ayvay Foy 4n element
valve and vetows its position:
const Fyvits = Crappie", tovange, "Apble’, “Mango” J;
lee position = eyoits.indexor (Apple +4
output 4
Javasevipt Away lastlndevo€ 0)
last metexofO returns ine position of the last occurance
Javascyipt Avvay Find 0
4. The find( methods yeturns the value oF the Flyst arvay
element that passes a test Function
let Fivst = numbers. Find (myeundien)
myFunttion 2 veturn 7 18
> @5) ourput-
dJavaswipt Avvay FindIindexC)
Findindext) returns tne index
let Fivst = numbevs: FindIndex Sela
JavaScript Arvay.Fvomt)
Avvay.Fvom () methods veturn an Avvay objet
const myaw = CABCDEEGH"),
Jet aw = Away.Fvem(myar)
tg) DAB C1, (DIE, FY NG HT
ae|
Tavasevipt Avways Keysc
Way Keys ©) > vehuyns an Avvay Tevatoy object with the Keys
oF an aay
Const myaw = C”apble". "Mango, “Lemon'") ;
Const aw = myavy. Keys ()
AA Verh wi
Foy (tet x op aw) §
text t=: x;
}
Output- 042
Avvay entviesc) = veturns key] yalves
const avy = myaw.entwies C)
OP ble tMango2,temon — output
Tavascvipt Avvay incudes ©)
avvay-indlodes €)-This allows us to check ifan elemetnr is
Pyesent in an avay
Const Fwirs = [”Banana’, "orange", “APple’ tango")
Fvoits-inciodes CMango") — Tvue
PSHPOLPHHRPPHKHPPHPPHPLHPHRSKRP HOB *R&2 Feet ecnennzeVPSPSSsesesessse Fs ssovyusoggeoggvouvovoovoreronee™
Javasevipt pate Objects
Const A= new pate)
Displaying Dates
The todatestvingc) methods convevts a date toa move
readable fymate
const d = new dated;
q. tobatestvingl);
console. log(d) -» wed Oct 26 2022
The touTestvingd) methods convevis a date to 4 Stying
Using the ote standavd
a. tourcstvingO; > wed,26 oct 2022 07 149217 GMT
The totsostving () > 2022-10-26T07:44:22.3592
Tavascvipt Get Date Methods
const d= new pared);
4. JerFull Yeay () > 2022
-getMontn() > 40
gerdate > 26
|. getHourvsd) > 13
-getSeconds() > 2
BerMilliseconds¢) > 684
Ea
3
4
5. JetMinotes() > 50
6
#
& gerDayl) > 3 let day =
dayst4.getDay() 3; wednesday
4, getTimecyTavaScvipt set Date Methods
A, serbate O
2. SetFuilyeavO
3. SerHouvd)
4.SetMillisecondO
5. Set Minotes C)
G. Set Mionth 0
7. Setseconds
@. SetTime ©)
——?. . ll p aae he=) =e eS ree vr FFT sTesTVvuVUVvGUUUSeeeeecee
2 A
TJavaScvipt Math Object
Math Methods
Math.metnod (number) -» syntax
Numbev to Integev
1 Math Yound (x) veturns tne neavest integer
Mathyound (4:5) = § 12345 6789
2. Math. ceil () vetuyns tne value of x Younded up toits neavest iat
Matn-ceil (4.2) 95 12245 6789
— Ora
3. Math.Floov(> veturns tne value of x rounded down to its ineeert ine |
Matn-looy (0-7) +4 4234567299
a
4. Math-tvuneO) veturns the integev pave of x:
Math. twun¢ (4-2) 9 4
5. Math.sigin (x) vetuns if x is negative, null ov positive
Math.sign (-4) — <4
6. Math. pous(x,y) yetuyns the value of x to the powev of y:
Math. pow) (#2) > 64
# Math -squr(s) > vetuins tne Sqvave vot oF x
Math-sqvt(64) > @
% Math-abs() veturns the absolute (positive) value oF x
Math.abs (-4.2) > 4
3. Math-sin() veturns the sine of the angie x (given in vadius)
Angle in vadios = Angie iv deqvee x Pl | 180
Math.sin (Qo «MathPi/igo): 1°
40. Math.cos ()
Matn-cos(o #Miarn p1(ie0)* 4
44, Math.min() 4 0,180, 30,20, -€,-200 — Find Jowest - 200)
Math.max()> Find Highest - (50)
42. Math. vandom (7
43. wlathlog()
[og2G) 3|
Java Scvibt Random
# Mathivandomnc) = ¥étuyne a random nordbev between
O inclusive), and 4 (exclusive)
COnsole log (Math.vandom()); if 0:0650664400242 LinGs
Nofe:-
note lath.vandom () always veturns a Nournbey lowey tan 4
2 TavaScvipt Ranelovn Integers
Math.yandornc) used wit, MatnFloov() can be used
to yetuyn vandom Integers -
>There is no such thing op Javascript integers.
> we talking about no. with no decimals Merve
Example 4
Return 9 Vandorn NUmbey (integer) From o to 9:
Math.Plooy (math. yandom(> # joy > a
Example 2
NWRetuyn a4 Yandom integey from o to 40;
Math -Eloor (math. vandomt) * 11); 59
Example 3
I] Return a vandom integey from o to \00.
Math: ¢looy (Math: vandom() ¥ 101); > 24
REPRE TLEHLICLLLILLLLPAR IIL I LPLSPLLLKPPISL SLL W«i i ee ee ee ee Oe a
CE E'S
Javascvipt 'F else, and else if
1. 16 (hovy <8) ¢
dveeting = “vied day
2. if Chovv cig) t
vee ting = "Good day";
Jelse &
greeting = “crodevening
i
3. else i¢
TE (time % 18) ¢
‘dveeting = “mood Moyning’.
Fese ic Gime c20)
Greeting = "ee0d day*;
Felse &
greeting = “moodevening";
3Javascvipt Switch Statement
switch(expvession) &
case x
byeak ;
case y
break;
?
Example
Switch (new patel) .getDay ()) £
case 0;
day= "Sunday";
break;
case 4:
day = "Monday";
ey ourpar - Wed.
ase2:
any = BS;
bveax;
cause.
day =" Wi";
break,
causes:
day = "PAU,
byeak;
case
day = "Evi";
break;
Case 6:
Aay = "Sat?PSHEESESELELELEECELEEEEEGEEOOOCOHOHONNNE””
Tavascevipt Fov Loop
Const cays = ("BMW") "Volvo". "Scaab’ ovd" Ji
feterenyas 7)
Foy (lebi=o; ig cays.lengrn; i++)
Fext += CaVSCIT
3
Console. log (text) — BMW, Volvo saab ,Fovad
Javascyipt Fov In Leob
const pevson = "7
for (ler x OF cays) &
eX aati xp
4
consore-lo.g (rext)ea i ede ee a Se ee eee eS
Tavascvipt Byeak and Continue
a \
Jomps out » Jumps-ovev
Aah ey | text
For (lebicos ic ios iat e Foy (ferizo; 1410; ir 4) E
3) Lbveakis | ie (i= ==3) Lontinves
3 Sa rext t= 4
console. log( text) 5
Consolelog (rext);
output - 012 Ovrpur- 9012456723Tavasevipt Type Conversion
4. Stvings to Number
console.tog (Nunbev("423")
aie
Console. log (Paysetnt 123")
Unavy + Opevaroy can be used to converka variable toa ne
console. log (ty peok (@"123" 9 numbey
Numbevs to stvings
Corisole.tog (ty PEOF (EOStving (12) a srving
3. Numbevs to Avvay
Input: 1234
ourput: £1,2.3,43
1. Method
Syntax
Avyay. From (object, mape” , this vale)
) let myint = 123
fevery Foy sueiiaua -oaNucnl cy AO
), myéune) 2
cons intaw = Away. From{siving (my int
console.log (intAYy) 3
01/2133Tavascipt Asyne
TavaScvipt Callbacks
"will cal back latey !"
as an avgunieut fo anofbev
cullbuck is & fometion passed
function
Tris feckngne allevo a Function fo Cull another fumction
A callback fumetion cam yun aftev qnothey fumition nas Praise
Function sequence
Eunction myFivsrhO
my Displayey (“Hello”)
i
function secondQ £
my Displayey (“noodbye’);
myFivst ©) second
seund 0) my Fist
Goodvye \yetlo yooutpee
Goodbye
Is Callback
Function myDisplayey (some) %
console. log (Some)
Bi
Function myCa\culatovCnumi, nvm jmyCallback ) £
let sum = num4 +nom2;
Wy Call back (sum) >
i)
my(altulatoy Cs, 5, myDisplayey); >
~~ y\ >» A Da anlasaiaaneilssaAn &>. 7 =~ ~ "= eveecreeevuecewvrvewuuvrvueyvywrrrreew
Asynchyonovs Tavascvipt
Waiting For a Timeout
When using the Javascvipt Function settimeout, you can
Sbeci-y a callback Function to be executed on time-out
- > is used as a Callback
Set Timeout (nyFunchon) 3000);
Fonction my Function() ¢
document.get Element Bytd (’derno").jnneyHTML = "F Love You;
myfuncton is passed to setTimeovt() as anavgumene
3000 ig ne number oF mills before Hme-ovt, So myFunction ©)
will be called aetev 3 seconds
Note: When you pass a gunction as an aygumen t, yemembey
not to use paventnes(s L)-
Waiting Foy Inievvals:
i i vu can
when using the Javascript eunctton setintevualé) , ¥
spediey A Callback Function to ve executed Foy each intevuot
nis used ab a Callen:
setintevvt (myFunction) £000)
Function myFunctionc) &
let d= new pateO;
docoment-getelementByrd ('demo').inney HTML =
d.getHovys@) 4 "3" germinutesO) "2" 4 agetseon ast
3
myfunction is passed to setmniewalO os an argument
4000 is me NOMbey OF MS ol intevvass , so myfuncion C)
will be called every secondTavaSevipt Evvor
Throw, and try -.. (aten.-. Findtly
> The tvy statement defines a Code to run (to 17¥)
> The catch statement degines a code block to handle
any eyvoy:
> The Finally statement defines a code block to
Yon vegardiess of tne yesolt
> The thyow statement aetines a cotom error
4+ Javascyipt tyy and catch
try ¢
If Block of Code te ty
3
Catun levy) £
Binuw of Code to handle evrors
i
+ Tavaswipt Throws Errors
>When an erroys occurs, Javascript will) normally stop
and genevate an evvoy message
let x= 53 let ye 20;
VE LK 410) threw "tv Jow":
te (4 > 10) throw "to nigh’;
uw The Finally Statement
tvy &
3
tak Un (YY) &
2)
Finally &
valew oF the tyy [Cth
Biout oF code to ve execured vega ater
ee 2 aS SyJavascvipt ISON
PRIERIA
TSON
i Fe
XS 9 Notation
JavaScvipt Object Le
&
What is TSON a
> TSON is a lightweight data-intevchange €ovmate es
> ISON 1s a plane text uvitten tn Tavascript object rota
TSoN Is used to send data between computevs 6
Tson is language independent ** rs
o
Ison method z
4. rson. stvingiFyO > convert object intoa stving- ~
Example: - i
const ob) = tname: "kamal", age: 225 ©:
const myJSoN = JSON. Stvingi Fy (Ab) te
console.1oq (mYyISON)2 I] £ "mame" Kamal", nage": 223 .
‘ é
2. TSON, pavse 0 > Payse He data with TSON-Paysé ©, ane ¢
the data becomes a Objecr- ‘
> Imagine we veceived iis text From 4 web Server: (
t
1 $name! Marna, veagels 223!
in ISON: parse ©) to convey &
> vse the Tava script aunt:
text into a objet
const 0b) = Ion. payse C
console: lo (oo) > gnames "¥owmal"’, age 223
ton gole.tog (obj.name) Kamat
gma": " vomal”, age” 223")OF FETC ESTEE SE ULUULE TEL LLLCLELEL EE SEES EE
4 Stoving Data
s$toving Data in \o
I stoving bara
const myodj = iv
const my Ison oJ
loco Sto-va ge seri re
WRetieving Dara
fet text = local
det Obj = ISON.
console. log (ob).
cal stuva 4e
samme: "Kamat", age
gon. stvingiFy(myae)) 7
mn (FESHISON” PySSON)
Stovage- getrtern ('restTSON");
payse (text);
acne) > Kawnet.Tavascvip Local Storage
Localstovage is a data Stovage type oF web Storaqe:
In snovt, ali we can say is that the locatstovage olds
the data with no expiry date
s Loca Stuvage Method
ats used to add the dara
to locasStovage:
1. setIteynv:- This metno
through Key and valve
2. getrrem(d:- It Ts used +o Fetch oy retvieve the valoe
from tne srovage using the key:
3, RermoveTiem(>:- tt vernoves an item Grom sporage
by using the Key:
je CR nose congo Clear al) ns
Storage:
Nefet= Each oF yrese metnods is used With locajstorage
keyword connecting with dot) character:
eer eS eS noosa saa
Foy Example: - Jacalstoyage. sett rer;
Remembey that locatstorage property is veact-only
4. Pedd Data
local S}orage- getitem ("name") Damat”);
2. (ret Data aay vegyived t
Jocad stovage.getr tem (mame); > Kamat
3. Remove Data Ny? vequived
local Stora ge-vernover tem name")
an (awe ede = Stee a tne Loclstovage date.
lo calStova yc, Cleay C)
2 eee