Java Script Lecturer Notes, Study notes of Javascript programming

An introduction to JavaScript, covering its history, capabilities, advantages, and limitations. It also discusses data types, operators, and statements in JavaScript, including conditional statements and switch statements. how to embed JavaScript in an HTML file and provides examples of arithmetic and string operators. useful for students studying web development or programming languages.

Typology: Study notes

2020/2021

Available from 04/20/2023

laxmiprasanna-muthyala
laxmiprasanna-muthyala 🇮🇳

1 document

1 / 58

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
JavaScript
JavaScriptisthepremierclient-side
interpretedscriptinglanguage
.Itswidelyusedin
tasks
rangingfrom thevalidationofform datatothecreationofcomplexuserinterfaces.
DynamicHTML
isacombinationofthecontentformattedusingHTML,CSS,Scripting
languageandDOM.Bycombiningallofthesetechnologies,wecancreateinteresting
andinteractivewebsites.HistoryofJavaScript:
NetscapeinitiallyintroducedthelanguageunderthenameLiveScriptinanearlybeta
releaseofNavigator2.0in1995,andthefocuswasonform validation.Afterthat,the
languagewasrenamedJavaScript.AfterNetscapeintroducedJavaScriptinversion2.0
oftheirbrowser,MicrosoftintroducedacloneofJavaScriptcalledJScriptinInternet
Explorer3.0.
WhataJavaScriptcando?
JavaScriptgiveswebdevelopersaprogramminglanguageforuseinwebpages&
allowsthemtodothefollowing:
JavaScriptgivesHTMLdesignersaprogrammingtool
JavaScriptcanbeusedtovalidatedata
JavaScriptcanreadandwriteHTMLelements
Createpop-upwindows
Perform mathematicalcalculationsondata
Reacttoevents,suchasauserrollingoveranimageorclickingabutton
Retrievethecurrentdateandtimefrom auserscomputerorthelasttimeadocument
wasmodified
Determinetheusersscreensize,browserversion,orscreenresolution
JavaScriptcanputdynamictextintoanHTMLpage
JavaScriptcanbeusedtocreatecookies
AdvantagesofJavaScript:
Lessserverinteraction
Immediatefeedbacktothevisitors
Increasedinteractivity
Richerinterfaces
Websurfersdontneedaspecialplug-intouseyourscripts
JavaScriptisrelativelysecure.
LimitationsofJavaScript:
WecannottreatJavaScriptasafull-fledgedprogramminglanguage.Itlackssomeof
theimportantfeatureslike:
Client-sideJavaScriptdoesnotallowthereadingorwritingoffiles.Thishasbeen
keptforsecurityreason.
JavaScriptcannotbeusedfornetworkingapplicationsbecausethereisnosuch
supportavailable.
JavaScriptdoesn'thaveanymultithreadingormultiprocesscapabilities.
Ifyourscriptdoesntworkthenyourpageisuseless.
Pointstoremember:
JavaScriptiscase-sensitive
Eachlineofcodeisterminatedbyasemicolon
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a

Partial preview of the text

Download Java Script Lecturer Notes and more Study notes Javascript programming in PDF only on Docsity!

JavaScript JavaScriptisthepremierclient-side interpretedscriptinglanguage.It‟swidelyusedin tasks rangingfrom thevalidationofform datatothecreationofcomplexuserinterfaces. DynamicHTMLisacombinationofthecontentformattedusingHTML,CSS,Scripting languageandDOM.Bycombiningallofthesetechnologies,wecancreateinteresting andinteractivewebsites.HistoryofJavaScript: NetscapeinitiallyintroducedthelanguageunderthenameLiveScriptinanearlybeta releaseofNavigator 2 .0in1 995 ,andthefocuswasonform validation.Afterthat,the languagewasrenamedJavaScript.AfterNetscapeintroducedJavaScriptinversion2. 0 oftheirbrowser,MicrosoftintroducedacloneofJavaScriptcalledJScriptinInternet Explorer 3. 0. WhataJavaScriptcando? JavaScriptgiveswebdevelopersaprogramminglanguageforuseinwebpages& allowsthem todothefollowing: JavaScriptgivesHTMLdesignersaprogrammingtool JavaScriptcanbeusedtovalidatedata JavaScriptcanreadandwriteHTMLelements Createpop-upwindows Perform mathematicalcalculationsondata Reacttoevents,suchasauserrollingoveranimageorclickingabutton Retrievethecurrentdateandtimefrom auser‟scomputerorthelasttimeadocument wasmodified Determinetheuser‟sscreensize,browserversion,orscreenresolution JavaScriptcanputdynamictextintoanHTMLpage JavaScriptcanbeusedtocreatecookies AdvantagesofJavaScript: Lessserverinteraction Immediatefeedbacktothevisitors Increasedinteractivity Richerinterfaces Websurfersdon‟tneedaspecialplug-intouseyourscripts JavaScriptisrelativelysecure. LimitationsofJavaScript: WecannottreatJavaScriptasafull-fledgedprogramminglanguage.Itlackssomeof theimportantfeatureslike: Client-sideJavaScriptdoesnotallowthereadingorwritingoffiles.Thishasbeen keptforsecurityreason. JavaScriptcannotbeusedfornetworkingapplicationsbecausethereisnosuch supportavailable. JavaScriptdoesn'thaveanymultithreadingormultiprocesscapabilities. Ifyourscriptdoesn‟tworkthenyourpageisuseless. Pointstoremember:  JavaScriptiscase-sensitive  Eachlineofcodeisterminatedbyasemicolon

 Variablesaredeclaredusingthekeywordvar  Scriptsrequireneitheramainfunctionnoranexitcondition.Therearemajor differencesbetweenscriptsand properprograms.Executionofascriptstarts withthefirstlineofcode&runsuntilthereisnomorecode JavaScriptcomments: InJavaScript,eachlineofcommentisprecededbytwoslashesandcontinuesfrom that pointtotheendoftheline. //thisisjavascriptcomment BlockcommentsorMultilinecomments:/**/ #JavaScriptisnotthesameasJava,whichisabiggerprogramminglanguage (althoughtherearesomesimilarities) JavaScriptandHTMLPage HavingwrittensomeJavaScript,weneedtoincludeitinanHTMLpage.Wecan‟t executethesescriptsfrom acommandline,astheinterpreterispartofthebrowser. Thescriptisincludedin thewebpageandrunbythebrowser,usuallyassoonasthe pagehasbeenloaded.Thebrowserisabletodebugthescriptandcandisplayerrors. EmbeddingJavaScriptinHTMLfile: Ifwearewritingsmallscripts,oronlyuseourscriptsinfewpages,thentheeasiestway istoincludethescriptintheHTMLcode.Thesyntaxisshownbelow:

……

JavaScriptProgramming Elements

  • Variables,datatypes,operators
  • Statements
  • Arrays
  • Functions
  • ObjectsinJavaScript
  • ExceptionHandling
  • Events
  • DynamicHTMLwithJavaScript

VARIABLES

Like anyprogramming language,JavaScripthas variables.A variable is a name assignedtocomputermemorylocationtostoredata.Asthenamesuggests,thevalue ofthevariablecanvary,astheprogram runs.Wecancreateavariablewiththevar statement: var=; Example: varsum = 0 ;varstr; Wecaninitializeavariablelikethis: str=“hello”; Rulesforvariablenames: #Theymustbeginwithaletter,digitorunderscorecharacter#Wecan‟tusespaces innames#Variablenamesarecasesensitive#Wecan‟tusereservedwordasa variablename. WeaklyTypedLanguage: Mosthigh-levellanguages,includingCandJava,are stronglytyped.Thatis,avariable mustbedeclaredbeforeitisused,anditstypemustbeincludedinitsdeclaration.Once avariableisdeclared,itstypecannotbechanged. AstheJavaScriptis weaklytypedlanguage,datatypesarenotexplicitlydeclared. Example:varnum; num = 3 ; num ="SanDiego"; First,whenthevariable num isdeclared,itisempty.Itsdatatypeisactuallythetype undefined.Thenweassignittothenumber 3 ,soitsdatatypeisnumeric.Nextwe reassignittothestring"SanDiego",sothevariable‟stypeisnowstring. Example:

vars; s=“Hello”; alert( typeof s);s=5 4321 ; alert( typeofs);

Arithmeticoperators:

Note:Iftheargumentsof+arenumbersthentheyareaddedtogether.Ifthe argumentsarestringsthentheyareconcatenatedandresultisreturned. Example:

txt 3 =txt1+txt 2 ; Relationaloperators/Comparisonoperators:Relationaloperatorsareusedtocompare

quantities.

ConditionalOperator:ConditionaloperatorisonetheJavaScript‟scomparisonoperator, whichassignsavaluetoavariablebasedonsomecondition. Syntax: variablename=(condition)?value 1 :value 2 ; Logicaloperators:Logicaloperatorsareusedtocombinetwoormoreconditions.

Example(Logicaloperators):

OperatorExample

Example: vars=“teststring”; alert( typeofs);//outputs“string” alert( typeof 95 );//outputs“number” alert( typeofwindow);//outputs “object”STATEMENTS Programsarecomposedoftwothings:dataandcode(setofstatements)which manipulatesthedata.JavascriptStatementscanbedividedintothefollowing categories:

  • ConditionalStatements
  • LoopingStatements
  • JumpingStatements

Conditionalstatements:Conditionalstatementsareusedtomake decisions.VariousconditionalstatementsinJavaScript: Variousformsofif switch Variousformsofif: Simpleif if-elseStatement nestedif else-ifladder Example:

ThisexampledemonstratestheIf...Elsestatement.

Ifthetimeonyourbrowserislessthan 10 ,youwillgeta"Goodmorning"greeting. Otherwiseyouwillgeta"Goodday"greeting.

Output:

switchstatement: Aswitchstatementallowsaprogram toevaluateanexpressionandattempttomatch theexpression'svaluetoacaselabel.Ifamatchisfound,theprogram executesthe associatedstatement. Syntax switch(expression) { caselabel 1 : block 1 break; caselabel 2 :block 2 break; …. default:defblock; } Example:

Loopingstatements:Loopsareusedtoexecutecertainstatementsrepeatedly.The variousloopsinJavaScriptare:

  • forloop
  • whileloop
  • do-whileloop

forloopsyntax: for(initialization;condition;loopvariableupdate) { Setofstatements } Example(forloop):

for-inloop: Thefor-inloophasaspecialusetoenumerateallthepropertiescontainedwithinanobject. ThisloopisrarelyusedinregularJavaScript. Example:Displaywindowobject propertiesvari,a=“”; for(iinwindow) a+=i+“…”; alert(a); whileloop:executesthestatementsaslongastheconditionistrue. Syntax:while(condition) { Setofstatements } Example:

vari= 0 ; while(i<= 10 ) { document.write("Thenumberis"+ i);document.write("
"); i=i+ 1 ; }

do-whilesyntax: do { Setofstatements }while(condition); JumpingStatements: breakstatement: breakstatementisusedtoterminatealoop,switch,orlabelstatement. Whenweusebreakwithoutalabel,itterminatestheinnermostenclosingwhile,do- while,for,orswitchimmediatelyandtransferscontroltothefollowingstatement. Whenweusebreakwithalabel,itterminatesthespecifiedlabeledstatement Syntax:

  • break;
  • break label;

continuestatement: Whenweusecontinuewithoutalabel,itterminatesthecurrentiterationofthe innermostenclosingwhile,do-whileorforstatementandcontinuesexecutionofthe loopwiththenextiteration. Whenweusecontinuewithalabel,itappliestotheloopingstatementidentifiedwiththat label. Syntax:

  • continue;
  • continue label;

WORKINGWITHARRAYS Anarrayisanorderedsetofdataelementswhichcanbeaccessedthroughasingle variablename.Inmanyprogramminglanguagesarraysarecontiguousareasof memorywhichmeansthatthefirstelementisphysicallylocatednexttothesecondand soon.InJavaScript,anarrayisslightlydifferentbecauseitisaspecialtypeofobject andhasfunctionalitywhichisnotnormallyavailableinotherlanguages.

Modifyingarrayelements: Arrayelementvaluescanbemodifiedveryeasily. Ex:Tochangea[ 1 ]valueto“vdc”simplywrite: a[ 1 ]=“vdc”; SearchinganArray: Tosearchanarray,simplyreadeachelementonebyone&compareitwiththevaluethat wearelookingfor. RemovingArrayMembers: JavaScriptdoesn‟tprovideabuiltinfunctiontoremovearrayelement.Todothis,we canusethefollowingapproach: readeachelementinthearray iftheelementisnottheoneyouwanttodelete,copyitintoatemporaryarray ifyouwanttodeletetheelementthendonothing incrementtheloopcounter repeattheprocess finallystorethetemporaryarrayreferenceinthemainarray variableNote:Thestatementdeletea[ 0 ]makesthevalueofa[ 0 ] undefinedOBJECT-BASEDARRAYFUNCTIONS: InJavaScript,anarrayisanobject.So,wecanusevariousmemberfunctionsofthe objecttomanipulatearrays. concat() Theconcat()methodreturnsthearrayresultingfrom concatenatingargumentarraysto thearrayonwhichthemethodwasinvoked.Theoriginalarraysareunalteredbythis process. Syntax:array 1 .concat(array 2 [,array 3 ,…arrayN]); Example:

join() join()methodallowstojointhearrayelementsasstringsseparatedbygiven specifier.Theoriginalarrayisunalteredbythisprocess. Syntax:arrayname.join(separator);

Example:

push() push()functionaddsoneormoreelementstotheendofanarrayandreturnsthelast elementadded. Syntax:arrayname.push(element 1 [,element 2 ,..elementN]); Example:

pop() pop()removesthelastelementfrom thearrayandreturnsthatelement Syntax:arrayname.pop(); reverse() reverse()methodtransposestheelementsofanarray:thefirstarrayelement becomesthelastandthelastbecomesthefirst.Theoriginalarrayisalteredbythis process. Syntax:arrayname.reverse(); Example:

shift() shift()removesthefirstelementofthearrayandindoingsoshortensitslengthbyone. Itreturnsthefirstelementthatisremoved. Ex:vara=[ 1 , 2 , 3 ]; varfirst=a.shift(); alert(a);// 2 , 3 alert(first);// 1

Example 1 : varmyArray=["cse","ece","eee"]; myArray.sort(); alert(myArray); Example 2 : vara=[ 80 , 732 , 450 ]; a.sort(); alert(a);// 450 , 732 , 80



STRINGS Stringisasetofcharactersencloseinapairofsinglequotesordoublequotes.In JavaScriptusingstringobject,manyusefulstringrelatedfunctionalitiescanbedone. Somecommonlyusedmethodsofstringobjectareconcatenatingtwostrings, convertingthestringtouppercaseorlowercase,findingthesubstringofagivenstring andsoon. PROPERTY: length Thispropertyofstringreturnsthelengthofthestring Example:“cmr”.length//gives 3 METHODS: charAt(index) Thismethodreturnsthecharacterspecifiedby indexExample:alert(“cmrcet”.charAt( 2 )); indexOf(substring[,offset]) Thismethodreturnstheindexofsubstringfoundinthemainstring.Ifthesubstringisnot foundreturns- 1 .BydefaulttheindexOf()functionstartsindex 0 ,however,anoptional offsetmaybespecified,sothatthesearchstartsfrom thatposition. Example:“cmrcet”.indexOf(“sv”); “Departmentof CSE”.indexOf(“CS”, 5 ); lastIndexOf(substring[,offset]) Thismethodreturnstheindexofsubstringfoundinthemainstring(i.e.last occurence).Ifthesubstringisnotfoundreturns- 1 .BydefaultthelastIndexOf() functionstartsatindexstring.length- 1 ,however,anoptionaloffsetmaybespecified, sothatthesearchstartsfrom thatpositioninbackwards. Example:“cmrcet”.lastIndexOf(“cet”);//returns “cmrcet”.lastIndexOf(“cet”, 6 );//returns

str 1 .concat(str 2 [,str 3 ..strN]) Thismethodisusedtoconcatenatestringstogether.Forexample,s 1 .concat(s 2 )returns theconcatenatedstringofs1ands 2 .Theoriginalstringsdon‟tgetalteredbythis operation.substring( start[ ,end]) Thismethodreturnsthesubstringspecifiedby startand endindices(upto endindex, butnotthecharacterat endindex).Ifthe endindexisnotspecified,thenthismethod returnssubstringfrom startindextotheendofthestring. Example:“vitsvecw”.substring( 3 , 6 );//returns sve“vitsvecw”.substring( 3 );//returnssvecw substr(index[,length]) Thismethodreturnssubstringofspecifiednumberofcharacters(length),starting from index.Ifthelengthisnotspecifieditreturnstheentiresubstringstartingfrom index. Example:“vitsvecw”.substr( 3 , 2 ); //returnssv“vitsvecw”.substr( 3 ); //returnssvecwtoLowerCase() returnsthestringinlowercase.Theoriginalstringisnotalteredbythisoperation. Example: toUpperCase() returnsthestringinuppercase.Theoriginalstringisnotalteredbythisoperation. Example: split(separator[,limit]) Splitsthestringbasedonthe separatorspecifiedandreturnsthatarrayofsubstrings.If thelimit isspecifiedonlythosenumberofsubstringswillbereturned Example 1 : vars="vit#svecw#bvrice#sbsp"; vart =s.split("#"); alert(t);