


















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 58
This page cannot be seen from the preview
Don't miss anything!



















































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
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: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:
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:
continuestatement: Whenweusecontinuewithoutalabel,itterminatesthecurrentiterationofthe innermostenclosingwhile,do-whileorforstatementandcontinuesexecutionofthe loopwiththenextiteration. Whenweusecontinuewithalabel,itappliestotheloopingstatementidentifiedwiththat label. Syntax:
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);