0% found this document useful (0 votes)
158 views

JavaScript Print Version - Wikibooks Open Books For An Open World PDF

Uploaded by

siriuslot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views

JavaScript Print Version - Wikibooks Open Books For An Open World PDF

Uploaded by

siriuslot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScript/Printversion

Contents
1Contents
2Introduction
2.1RelationtoJava
2.2Aboutthisbook
2.3Audience
3FirstProgram
3.1Exercises
3.1.1Exercise11
3.1.2Exercise12
4TheSCRIPTTag
4.1Thescriptelement
4.1.1Scriptinglanguage
4.2InlineJavaScript
4.2.1InlineHTMLcommentmarkers
4.2.2InlineXHTMLJavaScript
4.3Linkingtoexternalscripts
4.4Locationofscriptelements
4.5Reference
5Bookmarklets
5.1JavaScriptURIscheme
5.2Usingmultiplelinesofcode
5.3TheJavaScriptProtocolinLinks
5.4Examples
6LexicalStructure
6.1CaseSensitivity
6.2Whitespace
6.3Comments
6.4Semicolons
6.5Literals
6.6Identifiers
6.6.1Namingvariables
6.7References
7ReservedWords
7.1ReservedwordsusedinJavaScript
7.2WordsreservedforJavaScriptinthefuture
7.2.1Wordsthatarealwaysreserved
7.2.2Wordsthatarereservedinstrictmode
7.2.3WordsthatwerereservedinECMAScriptstandards13
7.3References
8VariablesandTypes
8.1Variabledeclaration
8.2Primitivetypes
8.2.1Booleantype
8.2.2Numerictypes
8.2.3Stringtypes
https://en.wikibooks.org/wiki/JavaScript/Print_version

1/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

8.3Complextypes
8.3.1Arraytype
8.3.2Objecttypes
8.4Scope
8.4.1Globalscope
8.4.2Localscope
8.5Seealso
8.6FurtherReading
9Numbers
9.1Basicuse
9.2TheMathobject
9.2.1Methods
9.2.1.1ceil(float)
9.2.1.2floor(float)
9.2.1.3max(int1,int2)
9.2.1.4min(int1,int2)
9.2.1.5random()
9.2.1.6round(float)
9.2.2Properties
9.3Furtherreading
10Strings
10.1Basicuse
10.2PropertiesandmethodsoftheString()object
10.2.1concat(text)
10.2.2length
10.2.3replace(text,newtext)
10.2.4slice(start[,end])
10.2.5substr(start[,numberofcharacters])
10.2.6substring(start[,end])
10.2.7toLowerCase()
10.2.8toUpperCase()
10.3Furtherreading
11Dates
11.1Propertiesandmethods
11.2FurtherReading
12Arrays
12.1Basicuse
12.1.1Exercise
12.2Nestedarrays
12.3PropertiesandmethodsoftheArray()object
12.3.1concat()
12.3.2join()andsplit()
12.3.3pop()andshift()
12.3.4push()andunshift()
12.4Furtherreading
13Operators
13.1Arithmeticoperators
13.2Bitwiseoperators
13.3Assignmentoperators
13.4Incrementoperators
13.4.1Preandpostincrementoperators
13.5Comparisonoperators
13.6Logicaloperators
13.7Otheroperators
13.7.1?:
https://en.wikibooks.org/wiki/JavaScript/Print_version

2/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

13.7.2delete
13.7.3new
13.7.4instanceof
13.7.5typeof
14ControlStructures
14.1Conditionalstatements
14.1.1if
14.1.2while
14.1.3dowhile
14.1.4for
14.2switch
14.3with
14.3.1Pros
14.3.2Cons
14.3.3Example
15FunctionsandObjects
16Functions
16.1Examples
16.1.1Basicexample
16.1.2"HelloWorld!"
16.1.3Extended"HelloWorld!"
16.2Functionswitharguments
17EventHandling
17.1EventHandlers
17.1.1EventAttributes
17.2Standardeventhandlers
17.3EventHandlersasHTMLattributes
18RegularExpressions
18.1Compatibility
18.2Matching
18.3Replacement
18.4Test
18.5Modifiers
18.6Operators
18.7Functioncall
18.8Seealso
18.9Externallinks
19Optimization
19.1JavaScriptOptimization
19.1.1OptimizationTechniques
19.2CommonMistakesandMisconceptions
19.2.1Stringconcatenation
20Debugging
20.1JavaScriptDebuggers
20.1.1Firebug
20.1.2VenkmanJavaScriptDebugger
20.1.3InternetExplorerdebugging
20.1.4Safaridebugging
20.1.5JTF:JavaScriptUnitTestingFarm
20.1.6jsUnit
20.1.7builtindebuggingtools
20.2CommonMistakes
20.3DebuggingMethods
20.3.1FollowingVariablesasaScriptisRunning
20.4BrowserBugs
https://en.wikibooks.org/wiki/JavaScript/Print_version

3/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

20.5browserdependentcode
20.6References
20.7Furtherreading
21DHTML
21.1alertmessages
21.2JavascriptButtonandAlertMessageExample:
21.3Javascriptif()elseExample
21.4TwoScripts
21.5SimpleCalculator
22FindingElements
22.1SimpleUse
22.2UseofgetElementsByTagName
23AddingElements
23.1BasicUsage
23.2FurtherUse
24ChangingElements
25RemovingElements
25.1References
26CodeStructuring
27Links
27.1Links
28UsefulSoftwareTools
28.1Editors/IDEs
28.2Enginesandothertools

Contents
1. Welcome
1. Introduction
2. FirstProgram
2. Basics
1. PlacingtheCode
1. Thescriptelement
2. Bookmarklets
2. LexicalStructure
1. ReservedWords
3. VariablesandTypes
1. NumbersStringsDatesArrays
4. Operators
5. ControlStructures
6. FunctionsandObjects
7. EventHandling
8. ProgramFlow
9. RegularExpressions

Introduction
https://en.wikibooks.org/wiki/JavaScript/Print_version

4/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScriptisaninterpretedcomputerprogramminglanguageformalizedintheECMAScriptlanguage
standard.JavaScriptenginesinterpretandexecuteJavaScript.JavaScriptenginesmaybedesignedforuse
asstandaloneinterpretors,embeddinginapplications,orboth.ThefirstJavaScriptenginewascreatedby
NetscapeforembeddingintheirWebbrowser.V8isaJavaScriptenginecreatedforuseinGoogleChrome
andmayalsobeusedasastandaloneinterpretor.AdobeFlashusesaJavaScriptenginecalledActionScript
fordevelopmentofFlashprograms.

RelationtoJava
JavaScripthasnorelationtoJavaasidefromhavingaClikesyntax.NetscapedevelopedJavaScript,and
SunMicrosystemsdevelopedJava.Therestofthissectionassumesabackgroundinprogramming.You
mayskiptothenextsection,ifyoulike.
Variableshaveastatictype(integerorstringforexample)thatremainsthesameduringthelifespanofa
runningprograminJava,andhaveadynamictype(NumberorStringforexample)thatcanchangeduring
thelifespanofarunningprograminJavaScript.VariablesmustbedeclaredpriortouseinJava,andhavea
undefinedvaluewhenreferredtopriortoassignmentinJavaScript.
Javahasanextensivecollectionoflibrariesthatcanbeimportedforuseinprograms.JavaScriptdoesnot
provideanymeanstoimportlibrariesorexternalJavaScriptcode.JavaScriptenginesmustextendthe
JavaScriptlanguagebeyondtheECMAScriptlanguagestandard,ifadditionalfunctionalityisdesired,such
astherequiredfunctionalityprovidedbyV8,ortheDocumentObjectModelfoundinmanyWebbrowsers.
Javaincludesclassesandobjectinstances,andJavaScriptusesprototypes.

Aboutthisbook
Thisbookiswrittenasatutorial,inthesensethatallkeyconceptsareexplained.Assuch,italsocontains
exercisesthatareclearlymarkedassuchattheendofapageorchapter.Answersfortheseexercisesare
alsoincluded.
Thebookcanalsobeusedasareference.Forthispurpose,allkeywordsarementionedanddescribed.

Audience
Thisbookassumesyouhavegoodknowledgeandsomeexperienceintheuseofcomputers,Webbrowsers,
texteditors,andsoftwaredevelopmentenvironments.AsyouwillnotlearnaboutHTML,CSS,Java,or
websitedesigninthisbook,consultanappropriatebooktolearnaboutthesesubjects.

FirstProgram
HereisasingleJavaScriptstatement,whichcreatesapopupdialogsaying"HelloWorld!":
alert("Hello World!");

https://en.wikibooks.org/wiki/JavaScript/Print_version

5/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Forthebrowsertoexecutethestatement,itmustbeplacedinsidea<script>element.Thiselement
describeswhichsectionoftheHTMLcodecontainsexecutablecode,andwillbedescribedinfurtherdetail
later.
<script type="text/javascript">
alert("Hello World!");
</script>

The<script>elementshouldthenbenestedinsidethe<head>elementofanHTMLdocument.Assuming
thepageisviewedinabrowserthathasJavaScriptenabled,thebrowserwillexecute(carryout)the
statementasthepageisloading.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Some Page</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
<p>The content of the web page.</p>
</body>
</html>

ThisbasichelloWorldprogramcanthenbeusedasastartingpointforanynewprogramsthatyouneedto
create.

Exercises
Exercise11
Copyandpastethebasicprograminafile,saveitonyourharddiskas"exercise11.html".Youcanrunit
intwoways:
1. Bygoingtothefilewithafilemanager,andopeningitusingawebbrowser(e.g.inWindows
Exploreritisdonewithadoubleclick)
2. Bystartingyourbrowser,andthenopeningthefilefromthemenu.ForFirefox,thatwouldbe:
ChooseFileinthemenu,thenOpenFile,thenselectthefile.
Whathappens?
Answer
Adialogappearswiththetext:HelloWorld!

Exercise12
Savethefileaboveas"exercise12.html".Replacethedoublequotesinthelinealert("HelloWorld!")
withsinglequotes,soitreadsalert('HelloWorld!')andsavetheresult.Ifyouopenthisfileinthebrowser,
whathappens?
Answer
https://en.wikibooks.org/wiki/JavaScript/Print_version

6/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Nothingchanges.Adialogappearswiththetext:HelloWorld!Thedoublequotesandthesinglequotes
areequivalent.

TheSCRIPTTag
Thescriptelement
AllJavaScript,whenplacedinanHTMLdocument,needstobewithinascriptelement.Ascript
elementisusedtolinktoanexternalJavaScriptfile,ortocontaininlinescripting(scriptsnippetsinthe
HTMLfile).AscriptelementtolinktoanexternalJavaScriptfilelookslike:
<script type="text/javascript" src="script.js"></script>

whileascriptelementthatcontainsinlineJavaScriptlookslike:
<script type="text/javascript">
// JavaScript code here
</script>

InlinescriptinghastheadvantagethatbothyourHTMLandyourJavaScriptareinonefile,whichis
convenientforquickdevelopmentandtesting.HavingyourJavaScriptinaseparatefileisrecommended
forJavaScriptfunctionsthatcanpotentiallybeusedinmorethanonepage,andalsotoseparatecontent
frombehaviour.

Scriptinglanguage
Thescriptelementwillworkinmostbrowsers,becauseJavaScriptiscurrentlythedefaultscripting
language.Itisstronglyrecommendedthoughtospecifywhattypeofscriptyouareusingincasethe
defaultscriptinglanguagechanges.
Thescriptinglanguagecanbespecifiedindividuallyinthescriptelementitself,andyoumayalsousea
metatagintheheadofthedocumenttospecifyadefaultscriptinglanguagefortheentirepage.
<meta http-equiv="Content-Script-Type" content="text/javascript" />

Whilethetext/javascriptwasformallyobsoletedinApril2006byRFC4329
(http://www.ietf.org/rfc/rfc4329.txt)[1]infavourofapplication/javascript,itisstillpreferableto
continueusingtext/javascriptduetooldHTMLvalidatorsandoldWebbrowserssuchasInternet
Explorer5thatareunabletounderstandapplication/javascript.[2]

InlineJavaScript
https://en.wikibooks.org/wiki/JavaScript/Print_version

7/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

UsinginlineJavaScriptallowsyoutoeasilyworkwithHTMLandJavaScriptwithinthesamepage.Thisis
commonlyusedfortemporarilytestingoutsomeideas,andinsituationswherethescriptcodeisspecificto
thatonepage.
<script type="text/javascript">
// JavaScript code here
</script>

InlineHTMLcommentmarkers
TheinlineHTMLcommentsaretopreventolderbrowsersthatdonotunderstandthescriptelementfrom
displayingthescriptcodeinplaintext.
<script type="text/javascript">
<!-// JavaScript code here
// -->
</script>

Olderbrowsersthatdonotunderstandthescriptelementwillinterprettheentirecontentofthescript
elementaboveasonesingleHTMLcomment,beginningwith"<!--"andendingwith"-->",effectively
ignoringthescriptcompletely.IftheHTMLcommentwasnotthere,theentirescriptwouldbedisplayedin
plaintexttotheuserbythesebrowsers.
Currentbrowsersthatknowaboutthescriptelementwillignorethefirstlineofascriptelement,ifit
startswith"<!--".Intheabovecase,thefirstlineoftheactualJavaScriptcodeisthereforetheline"//
JavaScript code here".
Thelastlineofthescript,"// -->",isaonelineJavaScriptcommentthatpreventstheHTMLend
commenttag"-->"frombeinginterpretedasJavaScript.
Theuseofcommentmarkersisrarelyrequirednowadays,asthebrowsersthatdonotrecognisethescript
elementarevirtuallynonexistent.TheseearlybrowserswereMosaic,Netscape1,andInternetExplorer2.
FromNetscape2.0inDecember1995andInternetExplorer3.0inAugust1996.Thosebrowserswereable
tointerpretJavaScript.[3]Anymodernbrowserthatdoesn'tsupportJavaScriptwillstillrecognizethe
<script>tagandnotdisplayittotheuser.

InlineXHTMLJavaScript
InXHTML,themethodissomewhatdifferent:
<script type="text/javascript">
// <![CDATA[
// [Todo] JavaScript code here!
// ]]>
</script>

Notethatboththe<![CDATA[tagsarecommentedout.The//preventsthebrowserfrommistakenly
interpretingthe<![CDATA[asaJavaScriptstatement(thatwouldbeasyntaxerror).

Linkingtoexternalscripts
https://en.wikibooks.org/wiki/JavaScript/Print_version

8/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScriptiscommonlystoredinafilesothatitmaybeusedbymanywebpagesonyoursite.Thismakes
itmucheasierforupdatestooccurandsavesspaceonyourserver.Thismethodisrecommendedfor
separatingbehavior(http://alistapart.com/articles/behavioralseparation)(JavaScript)fromcontent
((X)HTML)anditpreventstheissueofincompatibilitywithinlinecommentsinXHTMLandHTML.
Addsrc="script.js"totheopeningscripttag.Replacescript.jswiththepathtothe.jsfilecontaining
theJavaScript.
Becausetheserverprovidesthecontenttypewhenthefileisrequested,specifyingthetypeisoptional
whenlinkingtoexternalscripts.It'sstilladvisedtospecifythetypeastext/javascript,incasetheserver
isn'tsetupcorrectly,andtopreventHTMLvalidationcomplaints.
<script type="text/javascript" src="script.js"></script>

Locationofscriptelements
ThescriptelementmayappearalmostanywherewithintheHTMLfile.
Astandardlocationiswithintheheadelement.Placementwithinthebodyhoweverisallowed.
<!DOCTYPE html>
<html>
<head>
<title>Web page title</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<!-- HTML code here -->
</body>
</html>

Therearehoweversomebestpracticesforspeedingupyourwebsite[4]fromtheYahoo!Developer
Networkthatspecifyadifferentplacementforscripts,toputscriptsatthebottom
(http://developer.yahoo.com/performance/rules.html#js_bottom),justbeforethe</body>tag.Thisspeeds
updownloading,andalsoallowsfordirectmanipulationoftheDOMwhilethepageisloading.
<!DOCTYPE html>
<html>
<head>
<title>Web page title</title>
</head>
<body>
<!-- HTML code here -->
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Reference
1. RFC4329(http://www.ietf.org/rfc/rfc4329.txt):ScriptingMediaTypes
2. "application/javascript"and"application/ecmasscript"mediatypesnotrecognized.
(https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=338278)
3. w:JavaScript#Historyandnaming
https://en.wikibooks.org/wiki/JavaScript/Print_version

9/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

4. Yahoo:bestpracticesforspeedingupyourwebsite
(http://developer.yahoo.com/performance/rules.html)

Bookmarklets
BookmarkletsareonelinescriptsstoredintheURLfieldofabookmark.Bookmarkletshavebeenaround
foralongtimesotheywillworkinolderbrowsers.

JavaScriptURIscheme
YoushouldbefamiliarwithURLthatstartwithschemeslikehttpandftp,e.g.http://en.wikibooks.org/.
ThereisalsotheJavaScriptscheme,whichisusedtostarteverybookmarklet.
JavaScript:alert("Hello, World!");

Usingmultiplelinesofcode
Sinceyoucannothavelinebreaksinbookmarkletsyoumustuseasemicolonattheendofeachcode
statementinstead.
JavaScript:name=prompt("What is your name?")<font color="red">;</font>alert("Hello, " + name);

TheJavaScriptProtocolinLinks
TheJavaScriptprotocolcanbeusedinlinks.Thismaybeconsideredbadpractice,asitpreventsaccess
fororconfusesuserswhohavedisabledJavaScript.SeeBestPractices.
<a href="JavaScript:document.bgColor='#0000FF'">blue background</a>

Examples
Alargequantityoflinksmaybefoundonbookmarklets.com(http://www.bookmarklets.com/),which
showavarietyoffeaturesthatcanbeperformedwithinJavaScript.

LexicalStructure
CaseSensitivity
JavaScriptiscasesensitive.ThismeansthatHello()isnotthesameasHELLO()orhello()

Whitespace
https://en.wikibooks.org/wiki/JavaScript/Print_version

10/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Whitespacecanbe:extraindents,linebreaks,andspaces.JavaScriptignoresit,butitmakesthecodeeasier
forpeopletoread.
ThefollowingisJavaScriptwithverylittlewhitespace.
function filterEmailKeys(event){
event=event||window.event;
var charCode=event.charCode||event.keyCode;
var char=String.fromCharCode(charCode);
if(/[a-zA-Z0-9_\-\.@]/.exec(char))
return true;
return false;
}

ThefollowingisthesameJavaScriptwithatypicalamountofwhitespace.
function filterEmailKeys(event) {
event = event || window.event;
var charCode = event.charCode || event.keyCode;
var char = String.fromCharCode(charCode);
if (/[a-zA-Z0-9_\-\.@]/.exec(char)) {
return true;
}
return false;
}

ThefollowingisthesameJavaScriptwithalotofwhitespace.
function filterEmailKeys( evt )
{
evt = evt || window.event;
var charCode = evt.charCode || evt.keyCode;
var char = String.fromCharCode ( charCode );
if ( /[a-zA-Z0-9_\-\.@]/.exec ( char ) )
{
return true;
}
return false;
}

Comments
Commentsallowyoutoleavenotesinyourcodetohelpotherpeopleunderstandit.Theyalsoallowyouto
commentoutcodethatyouwanttohidefromtheparser,butyoudon'twanttodelete.
Singlelinecomments
Adoubleslash,//,turnsallofthefollowingtextonthesamelineintoacommentthatwillnotbe
processedbytheJavaScriptinterpreter.
// Shows a welcome message
alert("Hello, World!")

Multilinecomments
Multilinecommentsarebegunwithslashasterisk,/*,andendwiththereverseasteriskslash,*/.
https://en.wikibooks.org/wiki/JavaScript/Print_version

11/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Hereisanexampleofhowtousethedifferenttypesofcommentingtechniques.
/* This is a multi-line comment
that contains multiple lines
of commented text. */
var a = 1;
/* commented out to perform further testing
a = a + 2;
a = a / (a - 3); // is something wrong here?
*/
alert('a: ' + a);

Semicolons
Inmanycomputerlanguages,semicolonsarerequiredattheendofeachcodestatement.InJavaScriptthe
useofsemicolonsisoptional,asanewlineindicatestheendofthestatement.Thisiscalledautomatic
semicoloninsertion,andtherulesforitarequitecomplex.[1]Leavingoutsemicolonsandallowingthe
parsertoautomaticallyinsertthemcancreatecomplexproblems.
a=b+c
(d + e).print()

Theabovecodeisnotinterpretedastwostatements.Becauseoftheparenthesesonthesecondline,
JavaScriptinterpretstheaboveasifitwere
a = b + c(d + e).print();

wheninstead,youmayhavemeantittobeinterpretedas
a = b + c;
(d + e).print();

Eventhoughsemicolonsareoptional,it'spreferabletoendstatementswithasemicolontopreventany
misunderstandingsfromtakingplace.

Literals
Aliteralisahardcodedvalue.Literalsprovideameansofexpressingspecificvaluesinyourscript.For
example,attherightofequal:
var myLiteral = "a fixed value";

Thereareseveraltypesofliteralsavailable.Themostcommonarethestringliterals,buttherearealso
integerandfloatingpointliterals,arrayandbooleanliterals,andobjectliterals.
Exampleofanobjectliteral:
var myObject = { name:"value", anotherName:"anotherValue"};

DetailsofthesedifferenttypesarecoveredinVariablesandTypes.
https://en.wikibooks.org/wiki/JavaScript/Print_version

12/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Identifiers
Anidentifierisanameforapieceofdatasuchasavariable,array,orfunction.Therearerules:
Letters,dollarsigns,underscores,andnumbersareallowedinidentifiers.
Thefirstcharactercannotbeanumber.
Examplesofvalididentifiers:
u
$hello
_Hello
hello90
1A2B3Cisaninvalididentifier,asitstartswithanumber.

Namingvariables
Whennamingvariablestherearesomerulesthatmustbeobeyed:
Uppercaseandlowercaselettersofthealphabet,underscores,anddollarsignscanbeused
Numbersareallowedafterthefirstcharacter
Noothercharactersareallowed
Variablenamesarecasesensitive:differentcaseimpliesadifferentname
Avariablemaynotbeareservedword

References
1. StandardECMA262(http://www.ecmainternational.org/publications/files/ECMAST/Ecma
262.pdf)ECMAScriptLanguageSpecification,Chapter7.9AutomaticSemicolonInsertion

ReservedWords
ThispagecontainsalistofreservedwordsinJavaScript,whichcannotbeusedasnamesofvariables,
functionsorotherobjects.

ReservedwordsusedinJavaScript
CurrentlistofkeywordsusedinJavaScriptVersion5.1:[1]
break

delete

if

this

case

do

in

throw with

catch

else

instanceof try

continue finally new

typeof

debugger for

var

return

default function switch

while

void

https://en.wikibooks.org/wiki/JavaScript/Print_version

13/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

AfewotherreservedwordsusedinJavaScriptrepresentliteralvalues:[1]
false null true

WordsreservedforJavaScriptinthefuture
SomewordshavebeenreservedaccordingtotheECMAScriptspecificationsothattheycannotbeusedas
variablenames,althoughcurrently,theydonothaveanyfunctionality.Thesekeywordsmayormaynotbe
reservedwordsforsomeECMAScriptspecification,andaregroupedaccordingtotheirconditionofbeing
reserved.[2]

Wordsthatarealwaysreserved
await enum

Wordsthatarereservedinstrictmode
implements private

static

interface protected
package

public

WordsthatwerereservedinECMAScriptstandards13
abstract[citationneeded] extends

native[citationneeded]

boolean[citationneeded]

final[citationneeded] short[citationneeded]

byte[citationneeded]

float[citationneeded] super

char[citationneeded]

goto[citationneeded]

synchronized[citationneeded]

class

import

throws[citationneeded]

const

int[citationneeded]

transient[citationneeded]

double[citationneeded]

let

volatile[citationneeded]

export

long[citationneeded]

References
1. "ECMA2625.1:ECMAScriptLanguageSpecification"(http://www.ecmainternational.org/ecma
262/5.1/Ecma262.pdf)2011,Section7.6.1:ReservedWords,(keywords,thetwoBooleanliterals,
thenullliteral,andfuturereservedwords).
2. https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Lexical_grammar

VariablesandTypes
https://en.wikibooks.org/wiki/JavaScript/Print_version

14/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScriptisalooselytypedlanguage.Thismeansthatyoucanusethesamevariablefordifferenttypesof
information,butyoumayalsohavetocheckwhattypeavariableisyourself,ifthedifferencesmatter.For
example,ifyouwantedtoaddtwonumbers,butonevariableturnedouttobeastring,theresultwouldn't
necessarilybewhatyouexpected.

Variabledeclaration
Variablesarecommonlyexplicitlydeclaredbythevarstatement,asshownbelow:
var c;

Theabovevariableiscreated,buthasthedefaultvalueofundefined.Tobeofvalue,thevariableneedsto
beinitialized:
var c = 0;

Afterbeingdeclared,avariablemaybeassignedanewvaluethatwillreplacetheoldone:
c = 1;

Butmakesuretodeclareavariablewithvarbefore(orwhile)assigningtoitotherwiseyouwillcreatea
"scopebug."

Primitivetypes
Primitivetypesaretypesprovidedbythesystem,inthiscasebyJavaScript.PrimitivetypeforJavaScript
areBooleans,numbersandtext.Inadditiontotheprimitivetypes,usersmaydefinetheirownclasses.
TheprimitivetypesaretreatedbyJavaScriptasvaluetypesandwhenyoupassthemaroundtheygoas
values.Sometypes,suchasstring,allowmethodcalls.

Booleantype
Booleanvariablescanonlyhave2possiblevalues,trueorfalse.
var mayday = false;
var birthday = true;

Numerictypes
Youcanuseintegeranddoubletypesonyourvariables,buttheyaretreatedasanumerictype.
var sal = 20;
var pal = 12.1;

InECMAJavaScriptyournumberliteralscangofrom0to+1.79769e+308.Andbecause5e324isthe
smallestinfinitesimalyoucanget,anythingsmallerisroundedto0.

https://en.wikibooks.org/wiki/JavaScript/Print_version

15/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Stringtypes
TheStringandchartypesareallstrings,soyoucanbuildanystringliteralthatyouwishedfor.
var myName = "Some Name";
var myChar = 'f';

Complextypes
Acomplextypeisanobject,beiteitherstandardorcustommade.Itshomeistheheapandgoes
everywherebyreference.

Arraytype
InJavaScript,allArraysareuntyped,soyoucanputeverythingyouwantinanArrayandworryaboutthat
later.Arraysareobjects,theyhavemethodsandpropertiesyoucaninvokeatwill.Forexample,the
.lengthpropertyindicateshowmanyitemsarecurrentlyinthearray.Ifyouaddmoreitemstothearray,
thevalueofthe.lengthgetslarger.Youcanbuildyourselfanarraybyusingthestatementnewfollowed
byArray,asshownbelow.
var myArray = new Array(0, 2, 4);
var myOtherArray = new Array();

Arrayscanalsobecreatedwiththearraynotation,whichusessquarebrackets:
var myArray = [0, 2, 4];
var myOtherArray = [];

Arraysareaccessedusingthesquarebrackets:
myArray[2] = "Hello";
var text = myArray[2];

Thereisnolimittothenumberofitemsthatcanbestoredinanarray.

Objecttypes
AnobjectwithinJavaScriptiscreatedusingthenewoperator:
var myObject = new Object();

Objectscanalsobecreatedwiththeobjectnotation,whichusescurlybraces:
var myObject = {};

JavaScriptobjectscanbebuiltusinginheritanceandoverriding,andyoucanusepolymorphism.Thereare
noscopemodifiers,withallpropertiesandmethodshavingpublicaccess.Moreinformationoncreating
objectscanbefoundinObjectOrientedProgramming.
https://en.wikibooks.org/wiki/JavaScript/Print_version

16/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

YoucanaccessbrowserbuiltinobjectsandobjectsprovidedthroughbrowserJavaScriptextensions.

Scope
InJavaScript,thescopeisthecurrentcontextofthecode.Itreferstotheaccessabilityoffunctionsand
variables,andtheircontext.Thereexistsaglobalandalocalscope.Theunderstandingofscopeiscrucial
towritinggoodcode.Wheneverthecodeaccessesthis,itaccessestheobjectthat"owns"thecurrent
scope.

Globalscope
Anentitylikeafunctionoravariablehasglobalscopeifitisaccessiblefromeverywhereinthecode.
var a = 99;
function hello() {
alert("Hello, " + a + "!");
}
hello();
// prints the string "Hello, 99!"
alert(a);
// prints the number 99

Here,thevariableaisinglobalscopeandaccessiblebothinthemaincodepartandthefunctionhello()
itself.

Localscope
Alocalscopeexistswhenanentityisdefinedinacertaincodepart,likeafunction.
var a = 99;
function hello() {
var x = 5;
alert("Hello, " + (a + x) + "!");
}
hello();
// prints the string "Hello, 104!"
alert(a);
// prints the number 99
alert(x);
// throws an exception

Ifyouwatchthecodeonabrowser(onGoogleChrome,thisisachievedbypressingF12),youwillseean
Uncaught ReferenceError: x is not definedforthelastlineabove.Thisisbecausexisdefinedinthe
localscopeofthefunctionhelloandisnotaccessiblefromtheouterpartofthecode.

Seealso
Closures

FurtherReading
"Values,variables,andliterals".MDN.20130528.https://developer.mozilla.org/en
US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals.Retrieved20130620.

https://en.wikibooks.org/wiki/JavaScript/Print_version

17/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Numbers
JavaScriptimplementnumbersasfloatingpointvalues,thatis,they'reattainingdecimalvaluesaswellas
wholenumbervalues.

Basicuse
Tomakeanewnumber,asimpleinitializationsuffices:
var foo = 0; // or whatever number you want

Afteryouhavemadeyournumber,youcanthenmodifyitasnecessary.Numberscanbemodifiedor
assignedusingtheoperatorsdefinedwithinJavaScript.
foo = 1; //foo = 1
foo += 2; //foo = 3 (the two gets added on)
foo -= 2; //foo = 1 (the two gets removed)

Numberliteralsdefinethenumbervalue.Inparticular:
Theyappearasasetofdigitsofvaryinglength.
Negativeliteralnumbershaveaminussignbeforethesetofdigits.
Floatingpointliteralnumberscontainonedecimalpoint,andmayoptionallyusetheenotationwith
thecharactere.
Anintegerliteralmaybeprependedwith"0"toindicatethatanumberisinbase8.(8and9arenot
octaldigits,andiffound,causetheintegertobereadinthenormalbase10).
Anintegerliteralmayalsobefoundwithprefixed"0x"toindicateahexadecimalnumber.

TheMathobject
Unlikestrings,arrays,anddates,thenumbersaren'tobjects,sotheydon'tcontainanymethodsthatcanbe
accessedbythenormaldotnotation.InsteadacertainMathobjectprovidesusualnumericfunctionsand
constantsasmethodsandproperties.ThemethodsandpropertiesoftheMathobjectarereferencedusing
thedotoperatorintheusualway,forexample:
var varOne = Math.ceil(8.5);
var varPi = Math.PI;
var sqrt3 = Math.sqrt(3);

Methods
ceil(float)

Returnstheleastintegergreaterthanthenumberpassedasanargument.
var myInt = Math.ceil(90.8);
document.write(myInt); //91;

floor(float)
https://en.wikibooks.org/wiki/JavaScript/Print_version

18/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Returnsthegreatestintegerlessthanthenumberpassedasanargument.
var myInt = Math.floor(90.8);
document.write(myInt); //90;

max(int1, int2)

Returnsthehighestnumberfromthetwonumberspassedasarguments.
var myInt = Math.max(8, 9);
document.write(myInt); //9

min(int1, int2)

Returnsthelowestnumberfromthetwonumberspassedasarguments.
var myInt = Math.min(8, 9);
document.write(myInt); //8

random()

Generatesapseudorandomnumber.
var myInt = Math.random();

round(float)

Returnstheclosestintegertothenumberpassedasanargument.
var myInt = Math.round(90.8);
document.write(myInt); //91;

Properties
PropertiesoftheMathobjectaremostcommonlyusedconstantsorfunctions:
E:Returnstheconstante.
PI:Returnsthevalueofpi.
LN10:Returnsthenaturallogarithmof10.
LN2:Returnsthenaturallogarithmof2.
SQRT2:Returnsthesquarerootof2.

Furtherreading
JavaScriptMathObjectatMDN(https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Math)

https://en.wikibooks.org/wiki/JavaScript/Print_version

19/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Strings
Astringisatypeofvariablethatstoresastring(chainofcharacters).

Basicuse
Tomakeanewstring,youcanmakeavariableandgiveitavalueofnew String().
var foo = new String();

But,mostdevelopersskipthatpartanduseastringliteral:
var foo = "my string";

Afteryouhavemadeyourstring,youcanedititasyoulike:
foo = "bar";
foo = "barblah";
foo += "bar";

// foo = "bar"
// foo = "barblah"
// foo = "barblahbar"

Astringliteralisnormallydelimitedbythe'or"character,andcannormallycontainalmostany
character.Commonconventiondiffersonwhethertousesinglequotesordoublequotesforstrings.Some
developersareforsinglequotes(Crockford,Amaram,Sakalos,Michaux)whileothersarefordouble
quotes(NextApp,Murray,Dojo).Whichevermethodyouchoose,trytobeconsistentinhowyouapplyit.
Duetothedelimiters,it'snotpossibletodirectlyplaceeitherthesingleordoublequotewithinthestring
whenit'susedtostartorendthestring.Inordertoworkaroundthatlimitation,youcaneitherswitchtothe
othertypeofdelimiterforthatcase,orplaceabackslashbeforethequotetoensurethatitappearswithin
thestring:
foo = 'The cat says, "Meow!"';
foo = "The cat says, \"Meow!\"";
foo = "It's \"cold\" today.";
foo = 'It\'s "cold" today.';

PropertiesandmethodsoftheString()object
Aswithallobjects,Stringshavesomemethodsandproperties.
concat(text)

Theconcat()functionjoinstwostrings.
var foo = "Hello";
var bar = foo.concat(" World!")
alert(bar);
// Hello World!

length
https://en.wikibooks.org/wiki/JavaScript/Print_version

20/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Returnsthelengthasaninteger.
var foo = "Hello!";
alert(foo.length);

// 6

replace(text, newtext)

Thereplace()functionreturnsastringwithcontentreplaced.Onlythefirstoccurrenceisreplaced.
var foo = "foo bar foo bar foo";
var newString = foo.replace("bar", "NEW!")
alert(foo);
// foo bar foo bar foo
alert(newString);
// foo NEW! foo bar foo

Asyoucansee,thereplace()functiononlyreturnsthenewcontentanddoesnotmodifythe'foo'object.
slice(start[, end])

Sliceextractscharactersfromthestartposition,essentiallythesameassubstring
"hello".slice(1);

// "ello"

Whentheendisprovided,theyareextractedupto,butnotincludingtheendposition.
"hello".slice(1, 3);

// "el"

Sliceallowsyoutoextracttextreferencedfromtheendofthestringbyusingnegativeindexing.
"hello".slice(-4, -2); // "el"

Unlikesubstring,theslicemethodneverswapsthestartandendpositions.Ifthestartisaftertheend,
slicewillattempttoextractthecontentaspresented,butwillmostlikelyprovideunexpectedresults.
"hello".slice(3, 1);

// ""

substr(start[, number of characters])


substrextractscharactersfromthestartposition,essentiallythesameassubstring/slice.
"hello".substr(1);

// "ello"

Whenthenumberofcharactersisprovided,theyareextractedbycount.
"hello".substr(1, 3);

// "ell"

substring(start[, end])
substringextractscharactersfromthestartposition
https://en.wikibooks.org/wiki/JavaScript/Print_version

21/60

10/27/2015

"hello".substring(1);

JavaScript/Print version - Wikibooks, open books for an open world

// "ello"

Whentheendisprovided,theyareextractedupto,butnotincludingtheendposition.
"hello".substring(1, 3);

// "el"

substringalwaysworksfromlefttoright.Ifthestartpositionislargerthantheendposition,substring

willswapthevaluesalthoughsometimesuseful,thisisnotalwayswhatyouwantdifferentbehavioris
providedbyslice.
"hello".substring(3, 1);

// "el"

toLowerCase()

Thisfunctionreturnsthecurrentstringinlowercase.
var foo = "Hello!";
alert(foo.toLowerCase());

// hello!

toUpperCase()

Thisfunctionreturnsthecurrentstringinuppercase.
var foo = "Hello!";
alert(foo.toUpperCase());

// HELLO!

Furtherreading
JavaScriptStringObjectatMDN(https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/String)

Dates
ADateisanobjectthatcontainsagiventimetomillisecondprecision.
Unlikestringsandnumbers,thedatemustbeexplicitlycreatedwiththenewoperator.
var date = new Date(); // Create a new Date object with the current date and time.

TheDateobjectmayalsobecreatedusingparameterspassedtoitsconstructor.Bydefault,theDateobject
containsthecurrentdateandtimefoundonthecomputer,butcanbesettoanydateortimedesired.
var time_before_2000 = new Date(1999, 12, 31, 23, 59, 59, 999);

https://en.wikibooks.org/wiki/JavaScript/Print_version

22/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Thedatecanalsobereturnedasaninteger.ThiscanapplytoseedingaPRNGmethod,forexample.
var integer_date = +new Date; // Returns a number, like 1362449477663.

Thedateobjectnormallystoresthevaluewithinthelocaltimezone.IfUTCisneeded,thereareasetof
functionsavailableforthatuse.
TheDateobjectdoesnotsupportnonCEepochs,butcanstillrepresentalmostanyavailabletimewithin
itsavailablerange.

Propertiesandmethods
PropertiesandmethodsoftheDate()object:
getDate()

Returnsthedayofthemonth.[030]
getDay()

Returnsthedayoftheweekwithintheobject.[06].Sundayis0,withtheotherdaysoftheweek
takingthenextvalue.
getFullYear()

Retrievesthefull4digityearwithintheDateobject.
getMonth()

Returnsthecurrentmonth.[011]
parse(text)

Readsthestringtext,andreturnsthenumberofmillisecondssinceJanuary1,1970.
setFullYear(year)

Storesthefull4digityearwithintheDateobject.
setMonth(month, day)

SetsthemonthwithintheDateobject,andoptionallythedaywithinthemonth.[011].TheDate
objectuses0asJanuaryinsteadof1.

FurtherReading
JavaScriptDateObjectatMDN(https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Date)

Arrays
Anarrayisatypeofvariablethatstoresacollectionofvariables.ArraysinJavaScriptarezerobased
theystartfromzero.(insteadoffoo[1],foo[2],foo[3],JavaScriptusesfoo[0],foo[1],foo[2].)

Basicuse
Tomakeanewarray,makeavariableandgiveitavalueofnew Array().
var foo = new Array()

https://en.wikibooks.org/wiki/JavaScript/Print_version

23/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Afterdefiningit,youcanaddelementstothearraybyusingthevariable'sname,andthenameofthearray
elementinsquarebrackets.
foo[0] = "foo";
foo[1] = "fool";
foo[2] = "food";

Youcancallanelementinanarraythesameway.
alert(foo[2]); // outputs "food"

Youcandefineandsetthevaluesforanarraywithshorthandnotation.
var foo = ["foo", "fool", "food"];

Exercise
Makeanarraywith"zzz"asoneoftheelements,andthenmakeanalertboxusingthatelement.
Answer
var array = ["anton", "bertha", "caesar", "zzz"];
alert(array[3]);

Nestedarrays
Youcanputanarrayinanarray.
Thefirststepistosimplymakeanarray.Thenmakeanelement(ormore)ofitanarray.
var foo2 = new Array();
foo2[0] = new Array();
foo2[1] = new Array();

Tocall/defineelementsinanestedarray,usetwosetsofsquarebrackets.
foo2[0][0] = "something goes here";
foo2[0][1] = "something else";
foo2[1][0] = "another element";
foo2[1][1] = "yet another";
alert(foo2[0][0]);
// outputs "something goes here"

Youcanuseshorthandnotationwithnestedarrays,too.
var foo2 = [ ["something goes here", "something else"],
["another element", "yet another"] ];

Sothatthey'reeasiertoread,youcanspreadtheseshorthandnotationsacrossmultiplelines.
https://en.wikibooks.org/wiki/JavaScript/Print_version

24/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

var foo2 = [ ["something goes here", "something else"],


["another element", "yet another"]
];

PropertiesandmethodsoftheArray()object
concat()

Theconcat()methodreturnsthecombinationoftwoormorearrays.
Touseit,firstyouneedtwoormorearraystocombine.
var array1 = ["a", "b", "c"];
var array2 = ["d", "e", "f"];

Then,makeathirdarrayandsetitsvaluetoarray1.concat(array2).
var array3 = array1.concat(array2);

// array3 now is: ["a", "b", "c", "d", "e", "f"]

join()andsplit()

Thejoin()methodcombinesalltheelementsofanarrayintoasinglestring,separatedbyaspecified
delimiter.Ifthedelimiterisnotspecified,itissettoacomma.Thesplit()istheoppositeandsplitsup
thecontentsofastringaselementsofanarray,basedonaspecifieddelimiter.
Tousejoin(),firstmakeanarray.
var abc = ["a", "b", "c"];

Then,makeanewvariableandsetittoabc.join().
var a = abc.join();

// "a, b, c"

Youcanalsosetadelimiter.
var b = abc.join("; "); // "a; b; c"

ToconvertitbackintoanarraywiththeStringobject'ssplit()method.
var a2 = a.split(", "); // ["a", "b", "c"]
var b2 = b.split("; "); // ["a", "b", "c"]

pop()andshift()

Thepop()methodremovesandreturnsthelastelementofanarray.Theshift()methoddoesthesame
withthefirstelement.(Note:Theshift()methodalsochangesalltheindexnumbersofthearray.For
example,array[0]isremoved,array[1]becomesarray[0],array[2]becomesarray[1],andsoon.)
https://en.wikibooks.org/wiki/JavaScript/Print_version

25/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

First,makeanarray.
var array = ["0", "1", "2", "3"];

Thenusepop()orshift().
alert(array);
alert(array.pop());
alert(array);
alert(array.shift());
alert(array);

// outputs "0, 1, 2, 3"


// outputs "3"
// outputs "0, 1, 2"
// outputs "0"
// outputs "1, 2"

push()andunshift()

Thepush()andunshift()methodsreversetheeffectofpop()andshift().Thepush()methodaddsan
elementtotheendofanarrayandreturnsitsnewlength.Theunshift()methoddoesthesamewiththe
beginningofthearray(andlikeshift(),alsoadjuststheindexesoftheelements.)
array.unshift("0");
array.push("3");

// "0, 1, 2"
// "0, 1, 2, 3"

Furtherreading
JavaScriptArrayObjectatMDN(https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Array)

Operators
Arithmeticoperators
JavaScripthasthearithmeticoperators+,-,*,/,and%.Theseoperatorsfunctionastheaddition,
subtraction,multiplication,division,andmodulusoperators,andoperateverysimilarlytootherlanguages.
var a = 12 + 5;
var b = 12 - 5;
var c = 12*5;
var d = 12/5;
var e = 12%5;

// 17
// 7
// 60
// 2.4 - division results in floating point numbers.
// 2 - the remainder of 12/5 in integer math is 2.

Somemathematicaloperations,suchasdividingbyzero,causethereturnedvariabletobeoneoftheerror
valuesforexample,infinity,orNaN.
Thereturnvalueofthemodulusoperatormaintainsthesignofthefirstoperand.
The+and-operatorsalsohaveunaryversions,wheretheyoperateonlyononevariable.Whenusedinthis
fashion,+returnsthenumberrepresentationoftheobject,while-returnsitsnegativecounterpart.
var a = "1";
var b = a;

// b = "1": a string

https://en.wikibooks.org/wiki/JavaScript/Print_version

26/60

10/27/2015

var c = +a;
var d = -a;

JavaScript/Print version - Wikibooks, open books for an open world

// c = 1: a number
// d = -1: a number

+isalsousedasthestringconcatenationoperator:Ifanyofitsargumentsisastringorisotherwisenota

number,anynonstringargumentsareconvertedtostrings,andthe2stringsareconcatenated.For
example,5 + [1, 2, 3]evaluatestothestring"51, 2, 3".Moreusefully,str1 + " " + str2returns
str1concatenatedwithstr2,withaspacebetween.
Allotherarithmeticoperatorswillattempttoconverttheirargumentsintonumbersbeforeevaluating.Note
thatunlikeCorJava,thenumbersandtheiroperationresultsarenotguaranteedtobeintegers.

Bitwiseoperators
Therearesevenbitwiseoperators:&,|,^,~,>>,<<,and>>>.
Theseoperatorsconverttheiroperandstointegers(truncatinganyfloatingpointtowards0),andperform
thespecifiedbitwiseoperationonthem.Thelogicalbitwiseoperators,&,|,and^,performtheand,or,and
xoroneachindividualbitandprovidesthereturnvalue.The~(notoperator)invertsallbitswithinan
integer,andusuallyappearsincombinationwiththelogicalbitwiseoperators.
Twobitshiftoperators,>>,<<,movethebitsinonedirectionthathasasimilareffecttomultiplyingor
dividingbyapoweroftwo.Thefinalbitshiftoperator,>>>,operatesthesameway,butdoesnotpreserve
thesignbitwhenshifting.
Theseoperatorsarekeptforparitywiththerelatedprogramminglanguages,butareunlikelytobeusedin
mostJavaScriptprograms.

Assignmentoperators
Theassignmentoperator=assignsavaluetoavariable.Primitivetypes,suchasstringsandnumbersare
assigneddirectly,howeverfunctionandobjectnamesarejustpointerstotherespectivefunctionorobject.
Inthiscase,theassignmentoperatoronlychangesthereferencetotheobjectratherthantheobjectitself.
Forexample,afterthefollowingcodeisexecuted,"0,1,0"willbealerted,eventhoughsetAwaspassedto
thealert,andsetBwaschanged.Thisis,becausetheyaretworeferencestothesameobject.
setA = [ 0, 1, 2 ];
setB = setA;
setB[2] = 0;
alert(setA);

Similarly,afterthenextbitofcodeisexecuted,xisapointertoanemptyarray.
z = [5];
x = z;
z.pop();

Alltheaboveoperatorshavecorrespondingassignmentoperatorsoftheformoperator=.Forallofthem,x
operator=yisjustaconvenientabbreviationforx=xoperatory.

https://en.wikibooks.org/wiki/JavaScript/Print_version

27/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Arithmetic Logical Shift


+=

&=

>>=

-=

<<=

*=

^=

>>>=

/=
%=

Forexample,acommonusagefor+=isinaforloop
var els = document.getElementsByTagName('h2');
var i;
for (i = 0; i < els.length; i += 1) {
// do something with els[i]
}

Incrementoperators
Therearealsotheincrementanddecrementoperators,++and--.a++incrementsaandreturnstheold
valueofa.++aincrementsaandreturnsthenewvalueofa.Thedecrementoperatorfunctionssimilarly,
butreducesthevariableinstead.
Asanexample,thelastfourlinesallperformthesametask:
var a = 1;
a = a + 1;
a += 1;
a++;
++a;

Preandpostincrementoperators
Incrementoperatorsmaybeappliedbeforeorafteravariable.Whentheyareappliedbeforeoraftera
variable,theyarepreincrementorpostincrementoperators,respectively.Thechoiceofwhichtouse
changeshowtheyaffectoperations.
// increment occurs before a is assigned to b
var a = 1;
var b = ++a; // a = 2, b = 2;
// increment occurs to c after c is assigned to d
var c = 1;
var d = c++; // c = 2, d = 1;

Duetothepossiblyconfusingnatureofpreandpostincrementbehaviour,codecanbeeasiertoread,ifthe
incrementoperatorsareavoided.
// increment occurs before a is assigned to b
var a = 1;
a += 1;
var b = a; // a = 2, b = 2;
// increment occurs to c after c is assigned to d
var c = 1;
var d = c;
c += 1; // c = 2, d = 1;
https://en.wikibooks.org/wiki/JavaScript/Print_version

28/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Comparisonoperators
Thecomparisonoperatorsdetermine,ifthetwooperandsmeetthegivencondition.
Operator

Returns

Notes

true,ifthetwooperandsareequal

Mayignoreoperand'stype
(e.g.astringasaninteger)

===

true,ifthetwooperandsareidentical

Doesnotignoreoperands'types,and
only
returnstrueiftheyarethesametype
andvalue

!=

true,ifthetwooperandsarenotequal

Mayignoreanoperand'stype
(e.g.astringasaninteger)

true,ifthetwooperandsarenotidentical

Doesnotignoretheoperands'types,
andonly
returnsfalseiftheyarethesametype
andvalue.

==

!==

>

true,ifthefirstoperandisgreaterthanthesecond
one

>=

true,ifthefirstoperandisgreaterthanorequalto
thesecondone

<

true,ifthefirstoperandislessthanthesecondone

<=

true,ifthefirstoperandislessthanorequaltothe
secondone

Becarefulwhenusing==and!=,astheymayignorethetypeofoneofthetermsbeingcompared.Thiscan
leadtostrangeandnonintuitivesituations,suchas:
0 == '' // true
0 == '0' // true
false == 'false' // false; (''Boolean to string'')
false == '0' // true (''Boolean to string'')
false == undefined // false
false == null // false (''Boolean to null'')
null == undefined // true

Forstrictercomparesuse===and!==
0 === '' // false
0 === '0' // false
false === 'false' // false
false === '0' // false
false === undefined // false
false === null // false
null === undefined // false

Logicaloperators
&&and
||or
https://en.wikibooks.org/wiki/JavaScript/Print_version

29/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

!not

Thelogicaloperatorsareand,or,andnot.The&&and||operatorsaccepttwooperandsandprovidestheir
associatedlogicalresult,whilethethirdacceptsone,andreturnsitslogicalnegation.&&and||areshort
circuitoperators.Iftheresultisguaranteedafterevaluationofthefirstoperand,itskipsevaluationofthe
secondoperand.
Technically,theexactreturnvalueofthesetwooperatorsisalsoequaltothefinaloperandthatitevaluated.
Duetothis,the&&operatorisalsoknownastheguardoperator,andthe||operatorisalsoknownasthe
defaultoperator.
function handleEvent(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target && target.nodeType === 1 && target.nodeName === 'A') {
// ...
}
}

The!operatordeterminestheinverseofthegivenvalue,andreturnstheboolean:truevaluesbecomefalse,
orfalsevaluesbecometrue.
Note:JavaScriptrepresentsfalsebyeitheraBooleanfalse,thenumber0,anemptystring,orthebuiltin
undefinedornulltype.Anyothervalueistreatedastrue.

Otheroperators
?:

The?:operator(alsocalledthe"ternary"operator).
var target = (a == b) ? c : d;

Becautiousthoughinitsuse.Eventhoughyoucanreplaceverboseandcomplexif/then/elsechainswith
ternaryoperators,itmaynotbeagoodideatodoso.Youcanreplace
if (p && q) {
return a;
} else {
if (r != s) {
return b;
} else {
if (t || !v) {
return c;
} else {
return d;
}
}
}

with
return (p && q) ? a
: (r != s) ? b
: (t || !v) ? c
:d

https://en.wikibooks.org/wiki/JavaScript/Print_version

30/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Theaboveexampleisapoorcodingstyle/practice.Whenotherpeopleeditormaintainyourcode,(which
couldverypossiblybeyou,)itbecomesmuchmoredifficulttounderstandandworkwiththecode.
Instead,itisbettertomakethecodemoreunderstandable.Someoftheexcessiveconditionalnestingcan
beremovedfromtheaboveexample.
if (p && q) {
return a;
}
if (r != s) {
return b;
}
if (t || !v) {
return c;
} else {
return d;
}

delete
delete xunbindsx.

new
new clcreatesanewobjectoftypecl.Thecloperandmustbeaconstructorfunction.

instanceof
o instanceof ctestswhetheroisanobjectcreatedbytheconstructorc.

typeof
typeof xreturnsastringdescribingthetypeofx.Followingvaluesmaybereturned:[1]

Type

returns

boolean

"boolean"

number

"number"

null

"object"

string

"string"

undefined "undefined"

others

"object"

ControlStructures
ThecontrolstructureswithinJavaScriptallowtheprogramflowtochangewithinaunitofcodeor
function.Thesestatementscandeterminewhetherornotgivenstatementsareexecuted,aswellasrepeated
executionofablockofcode.

https://en.wikibooks.org/wiki/JavaScript/Print_version

31/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Mostofthestatementsenlistedbelowaresocalledconditionalstatementsthatcanoperateeitherona
statementorablockofcodeenclosedwithbraces({and}).ThesamestructuresutilizeBooleansto
determinewhetherornotablockgetsexecuted,whereanydefinedvariablethatisneitherzeronoran
emptystringistreatedastrue.

Conditionalstatements
if
Theifstatementisstraightforward&dashifthegivenexpressionistrue,thestatementorstatementswill
beexecuted.Otherwise,theyareskipped.
if (a === b) {
document.body.innerHTML += "a equals b";
}

Theifstatementmayalsoconsistofmultipleparts,incorporatingelseandelseifsections.Thesekeywords
arepartoftheifstatement,andidentifythecodeblocksthatareexecuted,iftheprecedingconditionis
false.
if (a === b) {
document.body.innerHTML += "a equals b";
} else if (a === c) {
document.body.innerHTML += "a equals c";
} else {
document.body.innerHTML += "a does not equal either b or c";
}

while
Thewhilestatementexecutesagivenstatementaslongasagivenexpressionistrue.Forexample,thecode
blockbelowwillincreasethevariablecto10:
while (c < 10) {
c += 1;
//
}

Thiscontrolloopalsorecognizesthebreakandcontinuekeywords.Thebreakkeywordcausesthe
immediateterminationoftheloop,allowingforthelooptoterminatefromanywherewithintheblock.
Thecontinuekeywordfinishesthecurrentiterationofthewhileblockorstatement,andchecksthe
conditiontosee,ifitistrue.Ifitistrue,theloopcommencesagain.

dowhile
Thedowhilestatementexecutesagivenstatementaslongasagivenexpressionistruehowever,
unlikethewhilestatement,thiscontrolstructurewillalwaysexecutethestatementorblockatleastonce.
Forexample,thecodeblockbelowwillincreasethevariablecto10:
do {
c += 1;
} while (c < 10);
https://en.wikibooks.org/wiki/JavaScript/Print_version

32/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Aswithwhile,breakandcontinuearebothrecognizedandoperateinthesamemanner.breakexitsthe
loop,andcontinuecheckstheconditionbeforeattemptingtorestarttheloop.

for
Theforstatementallowsgreatercontrolovertheconditionofiteration.Whileithasaconditional
statement,italsoallowsapreloopstatement,andpostloopincrementwithoutaffectingthecondition.The
initialexpressionisexecutedonce,andtheconditionalisalwayscheckedatthebeginningofeachloop.At
theendoftheloop,theincrementstatementexecutesbeforetheconditionischeckedonceagain.The
syntaxis:
for (<initial expression>;<condition>;<final expression>)

Theforstatementisusuallyusedforintegercounters:
var c;
for (c = 0; c < 10; c += 1) {
//
}

Whiletheincrementstatementisnormallyusedtoincreaseavariablebyoneperloopiteration,itcan
containanystatement,suchasonethatdecreasesthecounter.
Breakandcontinuearebothrecognized.Thecontinuestatementwillstillexecutetheincrementstatement
beforetheconditionischecked.
Asecondversionofthisloopisthefor..instatementthathasfollowingform:
for (element in object) {
//
}

Theorderofthegotelementsisarbitrary.ItshouldnotbeusedwhentheobjectisofArraytype

switch
Theswitchstatementevaluatesanexpression,anddeterminesflowcontrolbasedontheresultofthe
expression:
switch(i) {
case 1:
//
break;
case 2:
//
break;
default:
//
break;
}

Whenigetsevaluated,it'svalueischeckedagainsteachofthecaselabels.Thesecaselabelsappearinthe
switchstatementand,ifthevalueforthecasematchesi,continuestheexecutionatthatpoint.Ifnoneof
thecaselabelsmatch,executioncontinuesatthedefaultlabel(orskipstheswitchstatemententirely,if
noneispresent.)
https://en.wikibooks.org/wiki/JavaScript/Print_version

33/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Caselabelsmayonlyhaveconstantsaspartoftheircondition.
Thebreakkeywordexitstheswitchstatement,andappearsattheendofeachcaseinordertoprevent
undesiredcodefromexecuting.Whilethebreakkeywordmaybeomitted(forexample,youwantablock
ofcodeexecutedformultiplecases),itmaybeconsideredbadpracticedoingso.
Thecontinuekeyworddoesnotapplytoswitchstatements.
Omittingthebreakcanbeusedtotestformorethanonevalueatatime:
switch(i) {
case 1:
case 2:
case 3:
//
break;
case 4:
//
break;
default:
//
break;
}

Inthiscasetheprogramwillrunthesamecodeincaseiequals1,2or3.

with
Thewithstatementisusedtoextendthescopechainforablock[2]andhasthefollowingsyntax:
with (expression) {
// statement
}

Pros
Thewithstatementcanhelp
reducefilesizebyreducingtheneedtorepeatalengthyobjectreference,and
relievetheinterpreterofparsingrepeatedobjectreferences.
However,inmanycases,thiscanbeachievedbyusingatemporaryvariabletostoreareferencetothe
desiredobject.

Cons
Thewithstatementforcesthespecifiedobjecttobesearchedfirstforallnamelookups.Therefore
allidentifiersthataren'tmembersofthespecifiedobjectwillbefoundmoreslowlyina'with'block
andshouldonlybeusedtoencompasscodeblocksthataccessmembersoftheobject.
withmakesitdifficultforahumanoramachinetofindoutwhichobjectwasmeantbysearchingthe
scopechain.
Usedwithsomethingelsethanaplainobject,withmaynotbeforwardcompatible.
Therefore,theuseofthewithstatementisnotrecommended,asitmaybethesourceofconfusingbugsand
compatibilityissues.Seethe"AmbiguityCon"paragraphinthe"Description"sectionbelowfordetails.
https://en.wikibooks.org/wiki/JavaScript/Print_version

34/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Example
var area;
var r = 10;
with (Math) {
a = PI*r*r;
// == a = Math.PI*r*r
x = r*cos(PI);
// == a = r*Math.cos(Math.PI);
y = r*sin(PI/2); // == a = r*Math.sin(Math.PI/2);
}

FunctionsandObjects
Functions
Afunctionisanactiontotaketocompleteagoal,objective,ortask.Functionsallowyoutosplita
complexgoalintosimplertasks,whichmakemanagingandmaintainingscriptseasier.Aparameteror
argumentisdatawhichispassedtoafunctiontoeffecttheactiontobetaken.Functionscanbepassed
zeroormorearguments.Afunctionisexecutedwhenacalltothatfunctionismadeanywherewithinthe
script,thepage,anexternalpage,orbyanevent.Functionsarealwaysguaranteedtoreturnsomevalue
whenexecuted.Thedatapassedtoafunctionwhenexecutedisknownasthefunction'sinputandthevalue
returnedfromanexecutedfunctionisknownasthefunction'soutput.
AJavaScriptfunctionisacodeblockthatcanbereusedinsideanHTMLdocument.Afunctioncreatedin
anotherfilecannotbeincludedforreuse.Thefunctioncanbecalledviaanevent,orbymanualcalling.
Functionscanbeconstructedinthreemainways.Webeginwiththree"Hello,World!"examples:
Way1
function hello() {
alert("Hello, World!");
}

Way2
var hello = function() {
alert("Hello, World!");
};

Way3
var hello = new Function(
'alert("Hello, World!");'
);

Eachfunction:
canbecalledwithhello()
doesnotexpectanyarguments
performsanactiontoalerttheuserwithamessage
undefinedisreturnedwhenexecutionisfinished
Thehellofunctioncanbechangedtoallowyoutosayhellotosomeonespecificthroughtheuseof
arguments:
Way1
function hello(who) {
alert("Hello, " + who + "!");
}

Way2
var hello = function(who) {
alert("Hello, " + who + "!");
};

https://en.wikibooks.org/wiki/JavaScript/Print_version

Way3
var hello = new Function('who',
'alert("Hello, " + who + "!");'
);

35/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Eachfunction:
canbecalledwithhello()
expectsoneargumenttobepassed
performsanactiontoalerttheuserwithamessage
undefinedisreturnedwhenexecutionisfinished
Eachfunctioncanbecalledinseveralways:
Way1
hello("you");

Way2
hello.call(window, "you");

Way3
hello.apply(window, ["you"]);

Examples
Basicexample
function myFunction(string) {
alert(string);
document.innerHTML += string;
}
myFunction("hello");

Theexamplewouldfirst:
DefinethemyFunctionfunction
CallthemyFunctionfunctionwithargument"hello"
Theresult:
Analertmessagewith'hello'
Thestring'hello'beingaddedtotheendofthedocument's/page'sHTML.

"HelloWorld!"
Let'sputtogetherthe"HelloWorld!"codefromaboveonasampleWebpage.Thepagecallsthefunction
oncewhenthepageisloaded,andwheneverabuttonisclicked.
<html>
<head><title>Some Page</title></head>
<body>
<button id="msg">greeting</button>
<script type="text/javascript">

function hello() {
alert("Hello World!");
}
document.getElementById("msg").onclick = hello;
hello();

</script>
</body>
</html>
https://en.wikibooks.org/wiki/JavaScript/Print_version

36/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Extended"HelloWorld!"
Inthefollowingexample,thefunctionhellodoes"understand"whetheritiscalledwithaparametreornot,
andreturnsthegreetingwiththisparametre,orwiththeword"World":
<!DOCTYPE html>
<html>
<head><title>Extended Hello World!</title></head>
<body>
<button id="msg">greeting</button>
<script type="text/javascript">
function hello(who) {
if ((who == null)
|| (who.toString().search("object") >= 0)) {
who = "World";
}
alert("Hello " + who + "!");
}
document.getElementById("msg").onclick = hello;
hello("guy");
</script>
</body>
</html>

Functionswitharguments
Let'sstartwithaquickexample,thenwewillbreakitdown.
function stepToFive(number) {
if (number > 5) {
number -= 1;
}
if (number < 5) {
number += 1;
}
return number;
}

Thisprogramtakesanumberasanargument.Ifthenumberislargerthan5,itsubtractsone.Ifit'ssmaller
thanfiveitaddsone.Let'sgetdownanddirtyandlookatthispiecebypiece.
function stepToFive(number) {

Thisissimilartowhatwe'veseenbefore.Wenowhavenumberfollowingthefunctionname.Thisiswhere
wedefineourargumentsforlateruse,whichissimilartodefiningvariables,exceptinthiscasethe
variablesareonlyvalidinsideofthefunction.
if (number > 5) {

Ifstatements.Iftheconditionistrue,executethecodeinsidethecurlybrackets.
number -= 1;

https://en.wikibooks.org/wiki/JavaScript/Print_version

37/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

AssumingthatJavaScriptisyourfirstlanguage,youmightnotknowwhatthismeans.Thistakesoneoff
fromthevariablenumber.Youcanthinkofitasausefulshorthandfornumber = number - 1;.
number += 1;

Thisissimilartothelastone,exceptthatitaddsoneinsteadofsubtractingit.
return number;

Thisreturnsthevalueofnumberfromthefunction.Thiswillbecoveredinmoredepthlateron.
Hereisanexampleofusingthisinapage.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Some Page</title>
<script type="text/javascript">

function stepToFive(number) {
if (number > 5) {
number -= 1;
}
if (number < 5) {
number += 1;
}
return number;
}

</script>
</head>
<body>
<p>
<script type="text/javascript">

var num = stepToFive(6);


alert(num);

</script>
</p>
</body>
</html>

Thereareafewmorethingstocoverhere.
var num = stepToFive(6);

Thisiswherethereturnstatementinthefunctioncomesinhandy.numheregetsassignedthenumber5,
sincethatiswhatstepToFivewillreturnwhenit'sgivenanargumentof6.

EventHandling
https://en.wikibooks.org/wiki/JavaScript/Print_version

38/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

EventHandlers
Aneventoccurswhensomethinghappensinabrowserwindow.Thekindsofeventsthatmightoccurare
dueto:
Adocumentloading
Theuserclickingamousebutton
Thebrowserscreenchangingsize
Whenafunctionisassignedtoaneventhandler,thatfunctionisrunwhenthateventoccurs.
Ahandlerthatisassignedfromascriptusedthesyntax'[element].[event]=[function]',where[element]is
apageelement,[event]isthenameoftheselectedeventand[function]isthenameofthefunctionthat
occurswhentheeventtakesplace.
Forexample:
document.onclick = clickHandler;

ThishandlerwillcausethefunctionclickHandler()tobeexecutedwhenevertheuserclicksthemouse
anywhereonthescreen.Notethatwhenaneventhandlerisassigned,thefunctionnamedoesnotendwith
parentheses.Wearejustpointingtheeventtothenameofthefunction.TheclickHandlerfunctionis
definedlikethis:
function clickHandler(evt) {
//some code here
}

Byconventiontheeventisrepresentedbythevariable'evt'.Insomebrowserstheeventmustbeexplicitly
passedtothefunction,soasaprecautionit'softenbesttoincludeaconditionaltotestthattheevtvariable
hasbeenpassed,andifithasn'tthentouseanalternativemethodthatworksonthoseotherbrowsers:

function clickHandler(evt) {
evt = evt || window.event;
//some code here
}

Elementswithinadocumentcanalsobeassignedeventhandlers.Forexample:
document.getElementsByTagName('a')[0].onclick = linkHandler;

ThiswillcausethelinkHandler()functiontobeexecutedwhentheuserclicksthefirstlinkonthepage.
Keepinmindthatthisstyleofhandlerassignmentdependsonthelink'spositioninsidethepage.Ifanother
linktagisaddedbeforethisone,itwilltakeoverthehandlerfromtheoriginallink.Abestpracticeisto
maintaintheseparationofcodeandpagestructurebyassigningeachlinkanidentifierbyusingtheid
attribute.
<a id="faqLink" href="faq.html">Faq</a>

https://en.wikibooks.org/wiki/JavaScript/Print_version

39/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Ahandlerassignmentcanthenworkregardlessofwheretheelementispositioned.
document.getElementById('faqLink').onclick = linkHandler;

EventsareactionsthatcanbedetectedbyJavaScript,andtheeventobjectgivesinformationaboutthe
eventthathasoccurred.SometimeswewanttoexecuteaJavaScriptwhenaneventoccurs,suchaswhena
userclicksabutton.Eventsarenormallyusedincombinationwithfunctions,andthefunctionwillnotbe
executedbeforetheeventoccurs!JavaScripteventhandlersaredividedintotwotypes:
1. InteractiveeventhandlersdependsonuserinteractinwiththeHTMLpageex.Clickingabutton
2. NonInteractiveeventhandlersdoesnotneeduserinteraction.Ex.onload

EventAttributes
BelowistheeventattributesthatcanbeinsertedintodifferentHTMLelementstodefineeventactions.IE:
InternetExplorer,F:Firefox,O:Opera,W3C:W3CStandard.
Attribute

Theeventoccurswhen...

IE F O W3C

onblur

Anelementlosesfocus

1 9

Yes

onchange

Thecontentofafieldchanges 3

1 9

Yes

onclick

Mouseclicksanobject

1 9

Yes

ondblclick

Mousedoubleclicksanobject 4

1 9

Yes

onerror

Anerroroccurswhenloading
4
adocumentoranimage

1 9

Yes

onfocus

Anelementgetsfocus

1 9

Yes

onkeydown

Akeyboardkeyispressed

1 No Yes

onkeypress

Akeyboardkeyispressed
orhelddown

1 9

Yes

onkeyup

Akeyboardkeyisreleased

1 9

Yes

onload

Apageorimagehas
finishedloading

1 9

Yes

onmousedown Amousebuttonispressed

1 9

Yes

onmousemove Themouseismoved

1 9

Yes

onmouseout

Themouseismoved
offanelement

1 9

Yes

onmouseover

Themouseismoved
overanelement

1 9

Yes

onmouseup

Amousebuttonisreleased

1 9

Yes

onresize

Awindoworframeisresized 4

1 9

Yes

onselect

Textisselected

1 9

Yes

onunload

Theuserexitsthepage

1 9

Yes

Mouse/KeyboardAttributes:

https://en.wikibooks.org/wiki/JavaScript/Print_version

40/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Property

Description

IE F O W3C

altKey

Returnswhetherornotthe"ALT"
keywaspressedwhenanevent
wastriggered

1 9 Yes

button

Returnswhichmousebuttonwas
clickedwhenaneventwastriggered

1 9 Yes

clientX

Returnsthehorizontalcoordinateof
6
themousepointerwhenaneventwastriggered

1 9 Yes

clientY

Returnstheverticalcoordinateofthe
mousepointerwhenaneventwastriggered

1 9 Yes

ctrlKey

Returnswhetherornotthe"CTRL"key
waspressedwhenaneventwastriggered

1 9 Yes

metaKey

Returnswhetherornotthe"meta"key
waspressedwhenaneventwastriggered

1 9 Yes

relatedTarget

Returnstheelementrelatedtothe
elementthattriggeredtheevent

No 1 9 Yes

screenX

Returnsthehorizontalcoordinateofthe
mousepointerwhenaneventwastriggered

1 9 Yes

screenY

Returnstheverticalcoordinateofthemouse
pointerwhenaneventwastriggered

1 9 Yes

shiftKey

Returnswhetherornotthe"SHIFT"keywas
pressedwhenaneventwastriggered

1 9 Yes

OtherEventAttributes:
Property

Description

IE F O W3C

bubbles

ReturnsaBooleanvaluethatindicates
whetherornotaneventisabubblingevent

No 1 9 Yes

cancellable

ReturnsaBooleanvaluethatindicates
whetherornotaneventcanhave
itsdefaultactionprevented

No 1 9 Yes

currentTarget

Returnstheelementwhoseevent
listenerstriggeredtheevent

No 1 9 Yes

Returnstheelementthattriggeredtheevent

No 1 9 Yes

timeStamp

Returnsthetimestamp,inmilliseconds
No 1 9 Yes
fromtheepoch(systemstartoreventtrigger)

Standardeventhandlers

https://en.wikibooks.org/wiki/JavaScript/Print_version

41/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Attribute

Trigger

onabort

Loadingofimagewasinterrupted

onblur

Elementlosesfocus

onchange

Elementgetsmodified

onclick

Elementgetsclicked

ondblclick

Elementgetsdoubleclicked

onerror

Anerroroccurredloadinganelement

onfocus

Anelementreceivedfocus

onkeydown

Akeywaspressedwhenanelementhasfocus

onkeypress

Akeystrokewasreceivedbytheelement

onkeyup

Akeywasreleasedwhentheelementhasfocus

onload

Anelementwasloaded

onmousedown Themousebuttonwaspressedontheelement
onmousemove Themousepointermoveswhileinsidetheelement
onmouseout

Themousepointerwasmovedoutsidetheelement

onmouseover Themousepointerwasmovedontotheelement
onmouseup

Themousebuttonwasreleasedontheelement.

onreset

Theform'sresetbuttonwasclicked

onresize

Thecontainingwindoworframewasresized

onselect

Textwithintheelementwasselected

onsubmit

Aformisbeingsubmitted

onunload

Thecontentisbeingunloaded(e.g.windowbeingclosed)

onscroll

Theuserscrolls(inanydirectionandwithanymeans).

EventHandlersasHTMLattributes
InHTML,JavaScripteventscanbeincludedwithinanyspecifiedattributeforexample,abodytagcan
haveanonloadevent:
<body onload="alert('Hello world!');">

ThecontentoftheHTMLeventattributesisJavaScriptcodethatisinterpretedwhentheeventistriggered,
andworksverysimilarlytotheblocksofJavaScript.Thisformofcodeisusedwhenyouwanttohavethe
JavaScriptattacheddirectlytothetaginquestion.
ThistypeoftechniqueiscalledinlineJavaScript,andcanbeseenasbeingalessdesirabletechniquethan
otherunobtrusiveJavaScripttechniquesthathavepreviouslybeencovered.TheuseofinlineJavaScript
canbeconsideredtobesimilarinnaturetothatofusinginlineCSS,whereHTMLisstyledbyputtingCSS
instyleattributes.Thisisapracticethatisbestavoidedinfavourofmoreversatiletechniques.

RegularExpressions
https://en.wikibooks.org/wiki/JavaScript/Print_version

42/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScriptimplementsregularexpressions(regexforshort)whensearchingformatcheswithinastring.In
thefollowingexample,wearereplacingthewordbebythewordexistinatext:
1 var shakespeareText = "To be or not to be? That is the question.";
2
3 var regularExpression = new RegExp("be", "g");
4 var spoiltShakespeareText = shakespeareText.replace(regularExpression, "exist");
5
6 alert(spoiltShakespeareText);

Itwilldisplay:
Alert
Toexistornottoexist?Thatisthequestion.
Aswithotherscriptinglanguages,thisallowssearchingbeyondasimpleletterbylettermatch,andcan
evenbeusedtoparsestringsinacertainformat.Regularexpressionsmostcommonlyappearin
conjunctionwiththestring.match()andstring.replace()methods.Aregularexpressionobjectcanbe
createdwiththeRegExpconstructor.Thefirstparameteristhepatternandthesecondtheoptions:
1 var regularExpression = new RegExp("be", "g");

Alternatively,itcanbedelimitedbytheslash(/)character,andmayhavesomeoptionsappended:
1 var regularExpression = /be/g;

Compatibility
JavaScript'ssetofregularexpressionsfollowstheextendedset.Whilecopyingaregexpatternfrom
JavaScripttoanotherlocationmayworkproperly,someolderprogramsmaynotfunctionasexpected.
Inthesearchterm,\1isusedtobackreferenceamatchedgroup,asinotherimplementations.
Inthereplacementstring,$1issubstitutedwithamatchedgroupinthesearch,insteadof\1.
Example:"abbc".replace(/(.)\1/g, "$1") => "abc"
|ismagic,\|isliteral
(ismagic,\(isliteral
Thesyntaxes(?=...),(?!...),(?<=...),(?<!...)arenotavailable.

Matching
1 string = "Hello World!".match(/World/);
2 stringArray = "Hello World!".match(/l/g); // Matched strings returned in a string array
3 "abc".match(/a(b)c/)[1] => "b" // Matched subgroup is second member (=index "1") of resulting array

Replacement
1 string = string.replace(/expression without quotation marks/g, "replacement");
2 string = string.replace(/escape the slash in this\/way/g, "replacement");
3 string = string.replace( ... ).replace ( ... ). replace( ... );
https://en.wikibooks.org/wiki/JavaScript/Print_version

43/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Test
1 if (string.match(/regexp without quotation marks/)) {

Modifiers
Modifier

Note

Global.Thelistofmatchesisreturnedinanarray.

Caseinsensitivesearch

Multiline.Iftheoperandstringhasmultiplelines,^and$matchthebeginningandendof
eachlinewithinthestring,insteadofmatchingthebeginningandendofthewholestring
only.
"a\nb\nc".replace(/^b$/g,"d") => "a\nb\nc"
"a\nb\nc".replace(/^b$/gm,"d") => "a\nd\nc"

Operators
Operator

Effect

\b

Matchesboundaryofaword.

\w

Matchesanalphanumericcharacter,including"_".

\W

Negationof\w.

\s

Matchesawhitespacecharacter(space,tab,newline,formfeed)

\S

Negationof\s.

\d

Matchesadigit.

\D

Negationof\d.

Functioncall
Forcomplexoperations,afunctioncanprocessthematchedsubstrings.Inthefollowingcode,weare
capitalizingallthewords.Itcan'tbedonebyasimplereplacement,aseachlettertocapitalizeisadifferent
character:
1 var capitalize = function(matchobject) {
2
var group1 = matchobject.replace(/^(\W)[a-zA-Z]+$/g, "$1");
3
var group2 = matchobject.replace(/^\W([a-zA-Z])[a-zA-Z]+$/g, "$1");
4
var group3 = matchobject.replace(/^\W[a-zA-Z]([a-zA-Z]+)$/g, "$1");
5
return group1 + group2.toUpperCase() + group3;
6 };
7
8 var shakespeareText = "To be or not to be? That is the question.";
9
10 var spoiltShakespeareText = shakespeareText.replace(/\W[a-zA-Z]+/g, capitalize);
11
12 alert(spoiltShakespeareText);

Itwilldisplay:
https://en.wikibooks.org/wiki/JavaScript/Print_version

44/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Alert
ToBeOrNotToBe?ThatIsTheQuestion.
Thefunctioniscalledforeachsubstring.Hereisthesignatureofthefunction:
function (<matchedSubstring>[,<capture1>,...<captureN>,<indexInText>,<entireText>]) {

...
return<stringThatWillReplaceInText>;
}

Thefirstparameteristhesubstringthatmatchesthepattern,
Thenextparametersarethecapturesinthesubstrings.Thereareasmanyparametersasthereare
captures,
Thenextparameteristheindexofthebeginningofthesubstringstartingfromthebeginningofthe
text,
Thelastparameterisaremainderoftheentiretext,
Thereturnvaluewillbeputinthetextinsteadofthematchingsubstring.

Seealso
PerlRegularExpressionsReferenceachapterdevotedtoregularexpressionsinabookaboutthe
Perlprogramminglanguage.
RegularExpressionsaWikibookdedicatedtoregularexpressions.

Externallinks
JavaScriptRegExpObject(https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)atMDN.
JavaScriptRexExpTester(http://www.regularexpressions.info/javascriptexample.html)
RegularExpressionsinJavaScript
(http://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)atmozilla.org

Optimization
JavaScriptOptimization
OptimizationTechniques
HighLevelOptimization
AlgorithmicOptimization(MathematicalAnalysis)
Simplification
LowLevelOptimization
LoopUnrolling
StrengthReduction
https://en.wikibooks.org/wiki/JavaScript/Print_version

45/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Duff'sDevice
CleanLoops
ExternalTools&Librariesforspeeding/optimizing/compressingJavaScriptcode

CommonMistakesandMisconceptions
Stringconcatenation
StringsinJavaScriptareimmutableobjects.Thismeansthatonceyoucreateastringobject,tomodifyit,
anotherstringobjectmusttheoreticallybecreated.
Now,supposeyouwanttoperformaROT13onallthecharactersinalongstring.Supposingyouhavea
rot13()function,theobviouswaytodothismightbe:
var s1 = "the original string";
var s2 = "";
for(i = 0; i < s1.length; i++) {
s2 += rot13(s1.charAt(i));
}

EspeciallyinolderbrowserslikeInternetExplorer6,thiswillbeveryslow.Thisisbecause,ateach
iteration,theentirestringmustbecopiedbeforethenewletterisappended.
Onewaytomakethisscriptfastermightbetocreateanarrayofcharacters,thenjoinit:
var s1 = "the original string";
var a2 = new Array(s1.length);
var s2 = "";
for(i = 0; i < s1.length; i++) {
a2[i] = rot13(s1.charAt(i));
}
s2 = a2.join('');

InternetExplorer6willrunthiscodefaster.However,sincetheoriginalcodeissoobviousandeasyto
write,mostmodernbrowsershaveimprovedthehandlingofsuchconcatenations.Onsomebrowsersthe
originalcodemaybefasterthanthiscode.
Asecondwaytoimprovethespeedofthiscodeistobreakupthestringbeingwrittento.Forinstance,if
thisisnormaltext,aspacemightmakeagoodseparator:
var s1 = "the original string";
var c;
var st = "";
var s2 = "";
for(i = 0; i < s1.length; i++) {
c = rot13(s1.charAt(i));
st += c;
if(c == " ") {
s2 += st;
st = "";
}
}
s2 += st;

https://en.wikibooks.org/wiki/JavaScript/Print_version

46/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Thiswaythebulkofthenewstringiscopiedmuchlessoften,becauseindividualcharactersareaddedtoa
smallertemporarystring.
Athirdwaytoreallyimprovethespeedinaforloop,istomovethe[array].lengthstatementoutsidethe
conditionstatement.Inface,everyoccurrence,the[array].lengthwillberecalculateForatwooccurences
loop,theresultwillnotbevisible,but(forexample)inafivethousandoccurenceloop,you'llseethe
difference.Itcanbeexplainedwithasimplecalculation:
// we assume that myArray.length is 5000
for(x = 0;x < myArray.length;x++){
// doing some stuff
}

"x=0"isevaluatedonlyonetime,soit'sonlyoneoperation.
"x<myArray.length"isevaluated5000times,soitis10,000operations(myArray.lengthisanoperation
andcomparemyArray.lengthwithx,isanotheroperation).
"x++"isevaluated5000times,soit's5000operations.
Thereisatotalof15001operation.
// we assume that myArray.length is 5000
for(x = 0, l = myArray.length; x < l; x++){
// doing some stuff
}

"x=0"isevaluatedonlyonetime,soit'sonlyoneoperation.
"l=myArray.length"isevaluatedonlyonetime,soit'sonlyoneoperation.
"x<l"isevaluated5000times,soitis5000operations(lwithx,isoneoperation).
"x++"isevaluated5000times,soit's5000operations.
Thereisatotalof10002operation.
So,inordertooptimizeyourforloop,youneedtomakecodelikethis:
var s1 = "the original string";
var c;
var st = "";
var s2 = "";
for(i = 0, l = s1.length; i < l; i++) {
c = rot13(s1.charAt(i));
st += c;
if(c == " ") {
s2 += st;
st = "";
}
}
s2 += st;

Debugging
https://en.wikibooks.org/wiki/JavaScript/Print_version

47/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScriptDebuggers
Firebug
Firebug(http://www.getfirebug.com/)isapowerfulextensionforFirefoxthathasmanydevelopment
anddebuggingtoolsincludingJavaScriptdebuggerandprofiler.

VenkmanJavaScriptDebugger
VenkmanJavaScriptDebugger(http://www.hacksrus.com/~ginda/venkman/)(forMozillabased
browserssuchasNetscape7.x,Firefox/Phoenix/FirebirdandMozillaSuite1.x)
IntroductiontoVenkman
(http://web.archive.org/web/20040704044520/devedge.netscape.com/viewsource/2002/venkman/01/)
UsingBreakpointsinVenkman
(http://web.archive.org/web/20040603085323/devedge.netscape.com/viewsource/2003/venkman/01/)

InternetExplorerdebugging
MicrosoftScriptDebugger(http://msdn.microsoft.com/library/default.asp?url=/library/en
us/sdbug/Html/sdbug_1.asp)(forInternetExplorer)ThescriptdebuggerisfromtheWindows98and
NTera.IthasbeensucceededbytheDeveloperToolbar
InternetExplorerDeveloperToolbar(http://www.microsoft.com/downloads/details.aspx?
FamilyID=2f465be094fd4569b3c4dffdf19ccd99&displaylang=en)
MicrosoftsVisualWebDeveloperExpress(http://www.microsoft.com/express/vwd/)isMicrosofts
freeversionoftheVisualStudioIDE.ItcomeswithaJSdebugger.Foraquicksummaryofits
capabilitiessee[1](http://www.berniecode.com/blog/2007/03/08/howtodebugjavascriptwith
visualwebdeveloperexpress/)
InternetExplorer8(http://www.microsoft.com/windows/Internetexplorer/)hasafirebuglikeWeb
developmenttoolbydefault(noaddon)whichcanbeaccessedbypressingF12.TheWeb
developmenttoolalsoprovidestheabilitytoswitchbetweentheIE8andIE7renderingengines.

Safaridebugging
Safariincludesapowerfulsetoftoolsthatmakeiteasytodebug,tweak,andoptimizeawebsiteforpeak
performanceandcompatibility.Toaccessthem,turnontheDevelopmenuinSafaripreferences.These
includeWebInspector,ErrorConsole,disablingfunctions,andotherdeveloperfeatures.TheWeb
Inspectorgivesyouquickandeasyaccesstotherichestsetofdevelopmenttoolseverincludedina
browser.FromviewingthestructureofapagetodebuggingJavaScripttooptimizingperformance,the
WebInspectorpresentsitstoolsinacleanwindowdesignedtomakedevelopingwebapplicationsmore
efficient.Toactivateit,chooseShowWebInspectorfromtheDevelopmenu.TheScriptspanefeaturesthe
powerfulJavaScriptDebuggerinSafari.Touseit,choosetheScriptspaneintheWebInspectorandclick
EnableDebugging.ThedebuggercyclesthroughyourpagesJavaScript,stoppingwhenitencounters
exceptionsorerroneoussyntax.TheScriptspanealsoletsyoupausetheJavaScript,setbreakpoints,and
evaluatelocalvariables.[3]

JTF:JavaScriptUnitTestingFarm
JTF(http://jtf.ploki.info)isacollaborativewebsitethatenablesyoutocreatetestcasesthatwillbe
testedbyallbrowsers.It'sthebestwaytodoTDDandtobesurethatyourcodewillworkwellonall
browsers.

jsUnit
https://en.wikibooks.org/wiki/JavaScript/Print_version

48/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

jsUnit(http://www.jsunit.net/)

builtindebuggingtools
Somepeopleprefertosenddebuggingmessagestoa"debuggingconsole"ratherthanusethealert()
function[2](http://osteele.com/archives/2006/03/inlineconsole)[3]
(http://www.webreference.com/js/column108/5.html)[4](http://www.experts
exchange.com/Web/Web_Languages/JavaScript/Q_21380186.html).Followingisabrieflistofpopular
browsersandhowtoaccesstheirrespectiveconsoles/debuggingtools.
Firefox:Ctrl+Shift+Kopensanerrorconsole.
Opera(9.5+):Tools >> Advanced >> Developer ToolsopensDragonfly.
Chrome:Ctrl+Shift+Jopenschrome's"DeveloperTools"window,focusedonthe"console"tab.
InternetExplorer:F12opensafirebuglikeWebdevelopmenttoolthathasvariousfeaturesincluding
theabilitytoswitchbetweentheIE8andIE7renderingengines.
Safari:Cmd+Alt+CopenstheWebKitinspectorforSafari.

CommonMistakes
Carefullyreadyourcodefortypos.
Besurethatevery"("isclosedbya")"andevery"{"isclosedbya"}".
TrailingcommasinArrayandObjectdeclarationswillthrowanerrorinMicrosoftInternetExplorer
butnotinGeckobasedbrowserssuchasFirefox.
// Object
var obj = {
'foo' : 'bar',
'color' : 'red', //trailing comma
};
// Array
var arr = [
'foo',
'bar', //trailing comma
];

RememberthatJavaScriptiscasesensitive.Lookforcaserelatederrors.
Don'tuseReservedWordsasvariablenames,functionnamesorlooplabels.
Escapequotesinstringswitha"\"ortheJavaScriptinterpreterwillthinkanewstringisbeing
started,i.e:
alert('He's eating food');shouldbe
alert('He\'s eating food');or
alert("He's eating food");

WhenconvertingstringstonumbersusingtheparseIntfunction,rememberthat"08"and"09"(e.g.
indatetimes)indicateanoctalnumber,becauseoftheprefixzero.UsingparseIntusingaradixof10
preventswrongconversion.var n = parseInt('09',10);
RememberthatJavaScriptisplatformindependent,butisnotbrowserindependent.Becausethere
arenoproperlyenforcedstandards,therearefunctions,propertiesandevenobjectsthatmaybe
availableinonebrowser,butnotavailableinanother,e.g.Mozilla/GeckoArrayshaveanindexOf()
functionMicrosoftInternetExplorerdoesnot.

DebuggingMethods
https://en.wikibooks.org/wiki/JavaScript/Print_version

49/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

DebugginginJavaScriptdoesn'tdifferverymuchfromdebugginginmostotherprogramminglanguages.
SeethearticleatComputerProgrammingPrinciples/Maintaining/Debugging.

FollowingVariablesasaScriptisRunning
Themostbasicwaytoinspectvariableswhilerunningisasimplealert()call.Howeversomedevelopment
environmentsallowyoutostepthroughyourcode,inspectingvariablesasyougo.Thesekindof
environmentsmayallowyoutochangevariableswhiletheprogramispaused.

BrowserBugs
Sometimesthebrowserisbuggy,notyourscript.Thismeansyoumustfindaworkaround.
Browserbugreports(http://www.quirksmode.org/bugreports/)

browserdependentcode
SomeadvancedfeaturesofJavaScriptdon'tworkinsomebrowsers.
Toooftenourfirstreactionis:Detectwhichbrowsertheuserisusing,thendosomethingthecoolwayif
theuser'sbrowserisoneoftheonesthatsupportit.Otherwiseskipit.
Insteadofusinga"browserdetect",amuchbetterapproachistowrite"objectdetection"JavaScriptto
detectiftheuser'sbrowsersupportstheparticularobject(method,arrayorproperty)wewanttouse.[5]
(http://www.quirksmode.org/js/support.html)[6](http://pageresource.com/jscript/jobdet.htm)
Tofindoutifamethod,property,orotherobjectexists,andruncodeifitdoes,wewritecodelikethis:
var el = null;
if (document.getElementById) {
// modern technique
el = document.getElementById(id);
} else if (document.all) {
// older Internet Explorer technique
el = document.all[id];
} else if (document.layers) {
// older Netscape Web browser technique
el = document.layers[id];
}

References
1. "typeof"(inEnglish)(HTML).MozillaCorporation.20141118.Archivedfromtheoriginalon
20141118.https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Operators/typeof.
Retrieved20150305.
2. Sheppy,Shaveretal.(20141118)."with"(inEnglish)(HTML).Mozilla.Archivedfromthe
originalon20141118.https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Statements/with.Retrieved20150318.
3. "SafariThebestwaytoseethesites."(inEnglish)(HTML).Apple.
http://www.apple.com/safari/features.html#developer.Retrieved20150309.

Furtherreading
"JavaScriptDebugging"(http://www.mozilla.org/docs/webdeveloper/js/debugging/)byBen
https://en.wikibooks.org/wiki/JavaScript/Print_version

50/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Bucksch

DHTML
DHTML(DynamicHTML)isacombinationofJavaScript,CSSandHTML.

alertmessages
<script type="text/javascript">
alert('Hello World!');
</script>

Thiswillgiveasimplealertmessage.
<script type="text/javascript">
prompt('What is your name?');
</script>

Thiswillgiveasimplepromptmessage.
<script type="text/javascript">
confirm('Are you sure?');
</script>

Thiswillgiveasimpleconfirmationmessage.

JavascriptButtonandAlertMessageExample:
Sometimesitisbesttodigstraightinwiththecoding.Hereisanexampleofasmallpieceofcode:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>"THE BUTTON" - Javascript</title>
<script type="text/javascript">
x = 'You have not pressed "THE BUTTON"'
function bomb() {
alert('O-GOD NOOOOO, WE ARE ALL DOOMED!!');
alert('10');
alert('9');
alert('8');
alert('7');
alert('6');
alert('5');
alert('4');
alert('3');
alert('2');
alert('1');
alert('!BOOM!');
alert('Have a nice day. :-)');
x = 'You pressed "THE BUTTON" and I told you not to!';
}
</script>
<style type="text/css">
body {
background-color:#00aac5;
https://en.wikibooks.org/wiki/JavaScript/Print_version

51/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

color:#000
}
</style>
</head>
<body>
<div>
<input type="button" value="THE BUTTON - Don't Click It" onclick="bomb()"><br />
<input type="button" value="Click Here And See If You Have Clicked ''THE BUTTON''" onclick="alert(x)">
</div>
<p>
This script is dual-licensed under both, <a href="http://www.wikipedia.org/wiki/GNU_Free_Documentation_Licen
</p>
</body>
</html>

Whathasthiscodedone?Wellwhenitloadsittellswhatvaluethevariable'x'shouldhave.Thenextcode
snippetisafunctionthathasbeennamed"bomb".Thebodyofthisfunctionfiressomealertmessagesand
changesthevalueof'x'.
ThenextpartismainlyHTMLwithalittlejavascriptattachedtotheINPUTtags."onclick"propertytells
itsparentwhathastobedonewhenclicked.Thebombfunctionisassignedtothefirstbutton,thesecond
buttonjustshowsanalertmessagewiththevalueofx.

Javascriptif()elseExample

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


<html lang="en">
<head>
<title>The Welcome Message - Javascript</title>
<script type="text/javascript">
function wlcmmsg() {
name = prompt('What is your name?', '');
correct = confirm('Are you sure your name is ' + name + ' ?');
if (correct == true) {
alert('Welcome ' + name);
} else {
wlcmmsg();
}
}
</script>
<style type="text/css">
body {
background-color:#00aac5;
color:#000
}
</style>
</head>
<body onload="wlcmmsg()" onunload="alert('Goodbye ' + name)">
<p>
This script is dual-licensed under both, <a href="http://www.wikipedia.org/wiki/GNU_Free_Documentation_Licen
</p>
</body>
</html>

TwoScripts
Wearegoingbacktothefirstexample.Butaddingmoretothescriptbyalsoaddingadifferentwelcome
message.Thistimeapersonismadetoenteraname.Theyarealsoaskediftheywanttovisitthesite.
SomeCSShasalsobeenaddedtothebutton.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
https://en.wikibooks.org/wiki/JavaScript/Print_version

52/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

<head>
<title>"THE BUTTON" - Javascript</title>
<script type="text/javascript">
// global variable x
x = 'You have not pressed "THE BUTTON"';

function bomb() {
alert('O-GOD NOOOOO, WE ARE ALL DOOMED!!');
alert('3');
alert('2');
alert('1');
alert('!BOOM!');
alert('Have a nice day. :-)');
x = 'You pressed "THE BUTTON" and I told you not too!';
}
</script>
<style type="text/css">
body {
background-color:#00aac5;
color:#000
}
</style>
</head>
<body onload="welcome()">
<script type="text/javascript">
function welcome() {
var name = prompt('What is your name?', '');
if (name == "" || name == "null") {
alert('You have not entered a name');
welcome();
return false;
}
var visit = confirm('Do you want to visit this website?')
if (visit == true) {
alert('Welcome ' + name);
} else {
window.location=history.go(-1);
}
}
</script>
<div>
<input type="button" value="THE BUTTON - Don't Click It" onclick="bomb()" STYLE="color: #ffdd00; background<input type="button" value="Click Here And See If You Have Clicked ''THE BUTTON''" onclick="alert(x)">
</div>
<p>
This script is dual-licensed under both, <a href="http://www.wikipedia.org/wiki/GNU_Free_Documentation_Licen
</p>
</body>
</html>

SimpleCalculator
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Calculator</title>
<script type="text/javascript">
function multi() {
var a = document.Calculator.no1.value;
var b = document.Calculator.no2.value;
var p = (a*b);
document.Calculator.product.value = p;
}
function divi() {
var d = document.Calculator.dividend.value;
var e = document.Calculator.divisor.value;
var q = (d/e);
document.Calculator.quotient.value = q;
}
function circarea() {
https://en.wikibooks.org/wiki/JavaScript/Print_version

53/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

var r = document.Calculator.radius.value;
pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798
48233786783165;
var a = pi*(r*r);
document.Calculator.area.value = a;
var c = 2*pi*r;
document.Calculator.circumference.value = c;
}
</script>
<style type="text/css">
body {
background-color:#00aac5;
color:#000
}

label {
float:left;
width:7em
}
</style>
</head>
<body>
<h1>Calculator</h1>
<form name="Calculator" action="">
<fieldset>
<legend>Multiply</legend>
<input type="text" name="no1"> <input type="text" name="no2">
<input type="button" value="=" onclick="multi()">
<input type="text" name="product">
</fieldset>
<fieldset>
<legend>Divide</legend>
<input type="text" name="dividend"> <input type="text" name="divisor">
<input type="button" value="=" onclick="divi()">
<input type="text" name="quotient">
</fieldset>
<fieldset>
<legend>Area and Circumfrence of Circle</legend>
<p>(Uses pi to 240 d.p)</p>
<div>
<label for="radius">Type in radius</label> <input type="text" name="radius" id="radius" value="">
</div>
<div>
<input type="button" value="=" onclick="circarea()">
</div>
<div>
<label for="area">Area</label> <input type="text" name="area" id="area" value="">
</div>
<div>
<label for="circumference">Circumference</label> <input type="text" name="circumference" id="circumferen
</div>
</fieldset>
</form>
<p>Licensed under the <a href="http://www.gnu.org/licenses/gpl.html">GNU GPL</a>.</p>
</body>
</html>

FindingElements
ThemostcommonmethodofdetectingpageelementsintheDOMisbythe
document.getElementById(id)method.

SimpleUse
Let'ssay,onapage,wehave:
https://en.wikibooks.org/wiki/JavaScript/Print_version

54/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

<div id="myDiv">content</div>

AsimplewayoffindingthiselementinJavaScriptwouldbe:

var myDiv = document.getElementById("myDiv"); // Would find the DIV element by its ID, which in this case is 'myDi

UseofgetElementsByTagName
AnotherwaytofindelementsonawebpageisbythegetElementsByTagName(name)method.Itreturnsan
arrayofallnameelementsinthenode.
Let'ssay,onapage,wehave:
<div id="myDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<h1>An HTML header</h1>
<p>Paragraph 3</p>
</div>

UsingthegetElementsByTagNamemethodwecangetanarrayofall<p>elementsinsidethediv:
var myDiv = document.getElementById("myDiv"); // get the div
var myParagraphs = myDiv.getElementsByTagName('P'); //get all paragraphs inside the div

// for example you can get the second paragraph (array indexing starts from 0)
var mySecondPar = myParagraphs[1]

AddingElements
BasicUsage
UsingtheDocumentObjectModulewecancreatebasicHTMLelements.Let'screateadiv.
var myDiv = document.createElement("div");

WhatifwewantthedivtohaveanID,oraclass?
var myDiv = document.createElement("div");
myDiv.id = "myDiv";
myDiv.class = "main";

Andwewantitaddedintothepage?Let'susetheDOMagain
var myDiv = document.createElement("div");
myDiv.id = "myDiv";
myDiv.class = "main";
document.documentElement.appendChild(myDiv);
https://en.wikibooks.org/wiki/JavaScript/Print_version

55/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

FurtherUse
Solet'shaveasimpleHTMLpage
<html>
<head>
</head>
<body bgcolor="white" text="blue">
<h1> A simple Javascript created button </h1>
<div id="button"></div>
</body>
</html>

Wherethedivwhichhastheidofbutton,let'saddabutton.
myButton = document.createElement("input");
myButton.type = "button";
myButton.value = "my button";
placeHolder = document.getElementById("button");
placeHolder.appendChild(myButton);

AlltogethertheHTMLcodelookslike:
<html>
<head>
</head>
<body bgcolor="white" text="blue">
<h1> A simple Javascript created button </h1>
<div id="button"></div>
</body>
<script>
myButton = document.createElement("input");
myButton.type = "button";
myButton.value = "my button";
placeHolder = document.getElementById("button");
placeHolder.appendChild(myButton);
</script>
</html>

ThepagewillnowhaveabuttononitwhichhasbeencreatedviaJavaScript.

ChangingElements
InJavaScriptyoucanchangeelementsbyusingthefollowingsyntax:
element.attribute="new value"

Here,thesrcattributeofanimageischangedsowhenthescriptiscalled,itchangesthepicturefrom
myPicture.jpgtootherPicture.jpg.
//The HTML
<img id="example" src="myPicture.jpg">
//The JavaScript
document.getElementById("example").src="otherPicture.jpg";
https://en.wikibooks.org/wiki/JavaScript/Print_version

56/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

Inordertochangeanelement,youuseitsargumentnameforthevalueyouwishtochange.Forexample,
let'ssaywehaveabutton,andwewishtochangeitsvalue.
<input type="button" id="myButton" value="I'm a button!">

Lateroninthepage,withJavaScript,wecoulddothefollowingtochangethatbutton'svalue:

myButton = document.getElementById("myButton"); //searches for and detects the input element from the 'myButton' i
myButton.value = "I'm a changed button"; //changes the value

Tochangethetypeofinputitis(buttontotext,forexample),use:
myButton.type = "text"; //changes the input type from 'button' to 'text'.

Anotherwaytochangeorcreateanattributeistouseamethodlike
element.setAttribute("attribute", "value")orelement.createAttribute("attribute",
"value").UsesetAttribute/code> to change a attribute that has been defined before.
//The HTML
<div id="div2"></div> //Make a div with an id of div2 (we also could have made it with JavaScript)
//The Javascript
var e = document.getElementById("div2"); //Get the element
e.setAttribute("id", "div3"); //Change id to div3

But use createAttribute(), if you want to set a value that hasn't been defined before.
var e = document.createElement('div'); //Make a div element (we also could have made it with HTML)
e.createAttribute("id", "myDiv"); //Set the id to "myDiv"

RemovingElements
InJavaScript,anelementcanonlybedeletedfromitsparent.Todeleteone,youhavetogettheelement,
finditsparent,anddeleteitusingtheremoveChildmethod.[1]
Forexample,inaHTMLdocumentthatlookslike
<div id="parent">
<p id="child">I'm a child!</p>
</div>

ThecodeyouwouldneedtodeletetheelementwiththeID"child"wouldbe
// get elements
var child = document.getElementById("child");
var parent = document.getElementById("parent");
https://en.wikibooks.org/wiki/JavaScript/Print_version

57/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

// Delete child
parent.removeChild(child);

Insteadofgettingtheparentelementmanually,youcanusetheparentNodepropertyofthechildtofindits
parentautomatically.ThecodeforthisontheaboveHTMLdocumentwouldlooklike
// Get the child element node
var child = document.getElementById("child");
// Remove the child element from the document
child.parentNode.removeChild(child);

References
1. StackOverflow:JavaScript:removeelementbyid
(https://stackoverflow.com/questions/3387427/javascriptremoveelementbyid)

CodeStructuring

Links
Links
Featuredweblinks:
JavaScriptportal(http://developer.mozilla.org/enUS/docs/JavaScript)atdeveloper.mozilla.org
JavaScriptReference(http://developer.mozilla.org/enUS/docs/JavaScript/Reference)at
developer.mozilla.org
JavaScriptGuide(http://developer.mozilla.org/enUS/docs/JavaScript/Guide)at
developer.mozilla.org
GeckoDOMReference(http://mozilla.org/docs/dom/domref/dom_shortTOC.html)at
developer.mozilla.org
JavaScriptReference(http://msdn.microsoft.com/enus/library/ie/yek4tbz0%28v=vs.94%29.aspx)at
msdn.microsoft.com
Wikipedia:JavaScript
Wikipedia:ECMAScript
Wikipedia:JavaScriptengine
Wikiversity:Topic:JavaScript
Wikiversity:AdvancedJavaScript
https://en.wikibooks.org/wiki/JavaScript/Print_version

58/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

JavaScriptTutorial(http://www.w3schools.com/js/)atw3schools.com
JavaScriptReference(http://www.w3schools.com/jsref/default.asp)atw3schools.com
About:FocusonJavaScript(http://javascript.about.com/)fromStephenChapmanat
javascript.about.com
ecmascript.org(http://www.ecmascript.org/)
ecmainternational.org(http://www.ecmainternational.org/)
http://www.ecmainternational.org/publications/files/ECMAST/Ecma262.pdf
Discussionforums,bulletinboards:
HTML,CSSandJavaScript(http://www.coderanch.com/forums/f20/HTMLCSSJavaScript)at
coderanch.com
JavaScriptWorkshopforums(http://jsworkshop.com/bb/)atjsworkshop.com
Forum:Clientsidetechnologies(http://www.webxpertz.net/forums/forumdisplay.php/119Client
sidetechnologies)atwebxpertz.net
MoreWebsites:
JavaScripttutorials(http://webreference.com/programming/javascript/)atwebreference.com
Videos(http://www.youtube.com/results?hl=en&q=crockford%20javascript)fromw:Douglas
CrockfordonJavaScript(http://javascript.crockford.com/)
JavaScript(http://www.epanorama.net/links/pc_programming.html#javascript)atepanorama.net
JavaScriptTutorials(http://www.pickatutorial.com/tutorials/javascript_1.htm)atpickatutorial.com
JavaScriptEssentials(http://www.techotopia.com/index.php/JavaScript_Essentials)at
techotopia.comAnonlineJavaScriptbookdesignedtoprovideWebdeveloperswitheverything
theyneedtoknowtocreaterich,interactiveanddynamicWebpagesusingJavaScript.
JavaScriptTutorials(http://www.yourhtmlsource.com/javascript/)atyourhtmlsource.com
www.quirksmode.org(http://www.quirksmode.org)over150usefulpagesforCSSandJavascript
tips&crossbrowsercompatibilitymatrices.
Wiki:IwannaLearnJavaScript(http://c2.com/cgi/wiki?IwannaLearnJavaScript)atc2.comAlistof
linkstoWebresourcesonJavaScript
UnobtrusiveJavaScript(http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html)at
onlinetools.orgaguideonhowtowriteJavaScriptsothatyoursitedegradesgracefully(i.e.,ifthe
browserdoesnotsupportorhasturnedoffJavaScript,yoursiteisstillusable).

UsefulSoftwareTools
AlistofusefultoolsforJavaScriptprogrammers.

Editors/IDEs
AdobeBrackets:AnotherbrowserbasededitorbyAdobe
Eclipse:TheEclipseIDEincludesaneditoranddebuggerforJavaScript
Notepad++(http://notepadplus.sourceforge.net/uk/site.htm):AGreattoolforeditinganykindof
code,includessyntaxhighlightingformanyprogramminglanguages.
Programmers'Notepad(http://www.pnotepad.org/):Ageneraltoolforprogrammingmany
languages.
Scripted(https://github.com/scriptededitor/scripted):Anopensourcebrowserbasededitorby
SpringSource
SublimeText:OneofthemostusededitorsforHTML/CSS/JavaScriptediting
https://en.wikibooks.org/wiki/JavaScript/Print_version

59/60

10/27/2015

JavaScript/Print version - Wikibooks, open books for an open world

WebStormorIntelliJIDEA:bothIDEsincludeandeditoranddebuggerforJavaScript,IDEAalso
includesaJavadevelopmentplatform

Enginesandothertools
JSLint:staticcodeanalysisforJavaScript
jq(http://stedolan.github.io/jq/)"'jq'islikesedforJSONdata"
ListofECMAScriptengines
ListofReallyUsefulFreeToolsForJavaScriptDevelopers
(http://www.w3avenue.com/2009/05/19/listofreallyusefulfreetoolsforjavascriptdevelopers/)
Retrievedfrom"https://en.wikibooks.org/w/index.php?title=JavaScript/Print_version&oldid=2771136"

Thispagewaslastmodifiedon26February2015,at15:24.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicense.additionalterms
mayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.

https://en.wikibooks.org/wiki/JavaScript/Print_version

60/60

You might also like