Grand total:
Pay Nowe/a>
"js/example.js*>
On eeSUMMARY
BASIC JAVASCRIPT INSTRUCTIONS.EXAMPLE
BASIC JAVASCRIPT INSTRUCTIONS
Ea a/Js/eramptenis
// Greate variables for the welcove message
var greeting = "Howdy";
var name = ‘Molly's
var message = ', please check your order:';
// Concatenate the three variables above to create the welcone message
‘var welcome = greeting + nae + nessa;
Jf Greate variables to hold detatls about the sign
‘var sign = ‘Montague House's
var tiles = sign.lengt
var subTotal = tiles * 55
var shipping = 75
var grandTotal = subTotal + shipping:
J/ Get the elenent that has an id of greeting
‘var el = docunent .getélenentByld('greeting') ;
// Replace the content of that elenent with the personal ized welcone message
el. textContent = welcome;
// Get the elenent that has an id of userSign then update its contents.
‘var elSign = dociment.getE]enentById(*userSign')¢
elSign.textContent = sign;
// Get the elenent that has an id of tiles then update its contents
var elTiles = document getElenentByld(*tiTes');
elTiles.textContent = tiles;
J Get the elenent that has an 1d of subTotal then update its contents
‘var elSubTotal = docunent.getElenentByld{'subTotal');
elSubTotal.textContent = '5' + subTotal;
J/ Get the element that has an id of shipping then update its contents
‘var elSubTotal = docunent .getElenentById(' shipping"
elSubTotal.textContent = 'S' + shipping:
// Get the elenent that has an id of grandTotal then update its contents
var elGrandTotal = docunent .getElenent8yId (‘grandTotal");
elGrandTotal.textContent = ‘$* + grandTotal;
asic mvasenrineravcnions (@)SUMMARY
BASIC JAVASCRIPT INSTRUCTIONS
(@3) BASIC JAVASCRIPT INSTRUCTIONS.
FUNCTIONS,
METHODS &
OBJECTSBrowsers require very detailed instructions about what,
we want them to do. Therefore, complex scripts can run
to hundreds (even thousands) of lines. Programmers use
functions, methods, and objects to organize their code.
This chapter is divided into three sections that introduce:
FUNCTIONS & OBJECTS, BUILT-IN
METHODS OBJECTS
Functions consis ofa In Chapter yousaw that The browser comes with
sie of statements prowrammersuse bjects ast of objects that act
thathave been groupes __—_—tocreatemodelsaf he lea tol to creating
together because they word using data, andthat interactive web pages.
periorm aspecific task. objects are made up of This section introduces
Amethodisthe same 3s® properties and methods. __youtoanumber of ulin
function. exceptmethods _inthissection, youlearn “abject, wich you wil
recreated inside (andare how tocreateyourown then see used throughout
part of) an object. objects using JavaScript. theres ofthe book.
@ smerons nemons woesWHAT IS A FUNCTION?
Functions let you group a series of statements together to perform a
specific task. If different parts of a script repeat the same task, you can
reuse the function (rather than repeating the same set of statements).
Grouping together the
statements that are requited to
answer a question or perform a
taskhhelps organize your code
Furthermore, the statements ina
function ae not always executes
wena page loads, so functions
aso offer a way toto the steps
‘needed to achieve a task. The
script can then ask the function
te perform alot those steps as
and wien they are required,
For example, you might have
‘tos that younly went to
perform f the user clicks on a
pectic element the page
Ifyou ae going to ask the
function to perform ts task
later, you ned to give your
funtion aname. That ame
should describe the task tis
performing. When you skit
perform ts task, tis known 2s
calling the function.
‘The steps that the function
needs to perform in order to
perform ts task re packaged
‘pina code block. You may
remember from thelast chapter
that acode block consists of one
‘or mote statements contained
within curly braces. (And you do
‘ot writea semicolon after the
closing erly brace = ke you do
attr statement)
Some functions need tobe
provided with information in
‘arder to achiovea given task For
sample a function to caeulate
the aea of abox wouldneed
to know its width an height.
Pieces of information passed
toa lunetion ae known as
parameters
‘When you write function and
you expect ito provide you
with an answer, the response is
own 353 return value.
‘On the right theres an example
of afunetion in the JavaScript
file: scaled updatedessage().
Dorit wor ifyoudo not
understand the syrtaxof the
‘example onthe ight: you wll
‘take close look at how to write
and use functions inthe pages
that follow.
Remember that programming
languages often rely upon on
rname/vae pis. The function
has 8 name, updatekessage
and the vale is the code Bick
(ich consists of statements).
(Wen you cal the function by ts
fname, those statements wilrun
‘Yu canals have sronymous
functions. They donot have a
‘name 50 they cannot be called
Instead, they are executed as
soon a the interpreter comes
across them.A BASIC FUNCTION
Inthis example, the users Belore the closing
shownamessone atthe topo! tag, oun see the link tothe
‘the page. The meszage i el JavaScript ile. The JavaScript
InanHTML clement whose 1d _fllestarts with avarable used
attributehasa value ofmessage, _toholdenew message, andi
‘The message is ging tobe followed by afunction called
changed using JavaScript. updatenessase()
<1D0CTYPE heml>
Basic Functions/title>
elcone to our site!
ess /e03.css" />
ver msg = ‘Sign up to receive our newsletter for 10% off!
function updatetessage() (
var el » docunent.getETementByld(‘message");
el.textContent = sg;
)
updatetessage();
‘You do not need to wory about
how tis function works yet ~you
willearn abou that over the
ext few pages. For the moment,
‘tis just worth noting that inside
the curly braces ofthe function
are two statements,
03/basse-tuettor.hen
/s/tastectinetion.=
“These statements update the
message at the top ofthe page.
The function actslikeastoret
holds the statements that are
contained inthe curly braces
Lunt youre ready to use them.
“Those statements are not run
nt the function is alld. The
function's only called onthe last
line of hie sri
runerions,werwoos a onieersDECLARING A FUNCTION
ee eran OE ie ce une
Bee eee See ee ccs
See eeu sccm
Cee ee ey Se
cere rert) eee ee ee
ieee Caen)
SSS
sayHello() {
document .write('Hello!');
i
| __
ey er a eC et
een eee
Pec ners) o not need to repeat the same
pee en eet CO eee eee et
youwilseecrwrteare kelyto _thefunction to perform that task _usea function to doit and reuse
penance whenever needed, es)
een caryCALLING A FUNCTION
De ee ue ee ce eeu)
Dee enc eee
This is known as calling the function.
Ge emp ead cana Cee ey
pore ot eres Snes ar iretee nT EET ree
followed by parentheses function, a eee
Deere OL an ee
Instructions fora specctask. @)document.wite(‘Helo!"); function called before ithas
ate er } peereere er
Pena ee iad pete eenee tts
funetion eer
B.Thefunctonerectesthe ‘executing each statement
eee orn erect nets
Peers OV cac Perea ene nts
IF Code before bello...
poe Script. But forthe moment we
Poe estoy eres erica
re ern
Senet oa C))DECLARING FUNCTIONS
THAT NEED INFORMATION
Sometimes a function needs specific information to perform its task.
In such cases, when you declare the function you give it parameters.
Inside the function, the parameters act like variables,
ra
Perret
eens
function getArea reight) {
return width *
eee
Oey todCALLING FUNCTIONS
THAT NEED INFORMATION
MN ne ome cue ond
should use in the parentheses that follow its name. The values are called
arguments, and they can be provided as values or as variables.
EO eae)
Cee eet
bbeused forthe width ofthe wal and wil be use
forits height
Pere
PCa ae ot ah
eee eee
ec ie eee es
(nthe left-hand page, when the functions
coe eer eres
eee eee ete re
eee ea ee ees
re eee ee
PO RC
eee ec re
Se ete ee err
PSs eee eee
CO aes
CONT aly
getArea(wal width,
ee en
Cee eee eer re
eee ee eee a ey
eee re ater)
Sener
Ce eee eee oe
pe eee toe
eae cea)GETTING A SINGLE VALUE
OUT OF A FUNCTION
eee en ae cee
For example, when they perform a calculation, they return the result
ee ee Senet
ee ey et ee ee ee ed
poet eerei Renter hesernteed preter
function calculateArea(width, height) {
var area = width * height;
area;
STUN meaner Ke DY
STV UM MD a1a0 CS
Deen ee ee ee eee ete ee cece)
eee orn ear nar encanto)
See ee ee
eer eet ae ee
presen) Leeeeren einer)
een etaGETTING MULTIPLE VALUES
OUT OF A FUNCTION
Functions can return more than one value using an array.
eee eu eer eae od
Cee eer] Se eed
eres eee Poehe nes) cde that called the getSize()
rete tie ber eee ae eee ec ee ete)
Perera eee cette)
function getSize(width, height, depth) {
Cee mem iia
var volume = width * height * depth;
var sizes = [area, volume];
cla Res
i
PUTCO 11 Pere Uy
PEt CON A0 S51 (Marae)
ree es Se eee
eer tere? cone erenren
ey eer eR Ce
ears aa)ANONYMOUS FUNCTIONS
& FUNCTION EXPRESSIONS
Expressions produce a value. They can be used where values are expected.
fa function is placed where a browser expects to see an expression,
(eg,, as an argument to a function), then it gets treated as an expression.
FUNCTION DECLARATION
| function declaration creates function that you
‘ancallater in your code. Its the type of function
_yuhave sen ofr inthis book
In o-der toca the function aterin your code, you
must gveita name, so these are known as named
functions. Below. function called area() is
declared, which can then be called using its name,
FUNCTION EXPRESSION
IH you puta function where the interpreter would
‘expect to see an expression then ts treated as an
expression, and it sknown ae 2 function expression,
Infunction expressions, the name is usualy omitted.
‘function with no names clled on anonymous
function. Below, the function is stored ina variable
called area Itcan be called lke any function created
with function declaration.
function area(width, hefght) |
return width * heights
var size = aree(3,
var area = funetion(width, hetght) (
return width * heights
h
var size = area(s, 4s
‘As you will see on p56, the interpreter always
looks for variables an function declarations before
sping through each section ofa script ine-b-tn,
This means that a unetion created with a unetion
eciaraton can be called before it has even been
seciared
For mor information about how variables and
functions are processed fst, see the discussion
about execution contet ana hosting on
ps2 par.
Ina function expression, thefuction snot
processed unt the interpreter gets to that
statement. This means you cannet call ths function
bxfore tho interpreter has discovered it Italso means
that any code that appears upto that pont could
potently alter what goes on isi this uretionIMMEDIATELY INVOKED
FUNCTION EXPRESSIONS
This way of writing a function is used in several different situations.
Often functions are used to ensure that the variable names do not conflict
with each other (especially if the page uses more than one script).
IMMEDIATELY INVOKED FUNCTION
EXPRESSIONS (IIFE)
Proncunced “ify these functions are nt given
name. instead they are executed ance asthe
Interreter comes across them,
Below, the variable called area wil hold he valve
returned from the funtion (rather than storing the
function tel so that it ean be called late
var orea = ffuntion() (
var width =
var height
return width * heights
“The final parentheses (shown on green) after
the closing curly brace of the code back tllthe
Interpreter to calle function immediately
‘The grouping operators (shown on pak) are
parentheses there toensurethe ntreprter treats
this as an expression.
‘You may se the final parentheses in an FE
placed oterthe closing grouping operator but it
‘= commonly considered btter practice to place
the final parentheses before the closing aroun
‘operat, 2 shown in the code above.
WHEN TO USE ANONYMOUS
FUNCTIONS AND IIFES
‘You wil se many ways in which anonymous
function expressions and lIFEs are used throughout
the book
‘They are used for code that only needs to run once
within task rather than repeatedly being called by
‘other parts of the seit. For examgl:
‘© Asan argument when 2 function iscalled
(to caleulate a value for tat funtion.
‘© Toassign the valve ofa property to an object.
1 Ineventhendlers and listeners (ee Chapter 6)
toperform a task when an event occurs
{© Toprevent cones between two scripts that
right use the same variable names (see p99)
IFEs are commonly used as 2 wrapper around 3
set of code. Any variables declared within that
‘anonymous funtion ae eltectvely protected rom
variables nother scripts that might have the same
name. This is due toa concept called scope which
you mest onthe next page It isalso avery popular
technique with jQuery.VARIABLE SCOPE
The location where you declare a variable will affect where it can be used
within your code. If you declare it within a function, it can only be used
within that function. This is known as the variable’s scope.
LOCAL VARIABLES
When a variables created inside a function using the
var keyword itcan only be used that function.
Its called a oeal variable o«funetion-level arabe
Its sa to have local scope or function level scope.
cannot be accessed outside ofthe funeton in
‘which it as declared, Below. area isa local variable.
The interpreter creates local variables when the
function sun, and removes them as so0n asthe
function ha firiahed ts tsk, This means that
1 Ifthe function runs twice, the variable can have
diterent values each tine
‘# Two diferent functions can use variables with the
same name without any kindof naming conti.
GLOBAL VARIABLES
you create variable ousie of a function then
canbeused anywhere within the script tis called
slobal variable ard has global scope. Inthe example
shown, wal) Sizeis a global variable
(Global variables are stored in memory for a ong
asthe web page is loaded into the web browser.
This means they take up more memory than local
variables, and aso increases the sk of naming
conflicts seenext page), For these reasons, you
should use local variables wherever possible.
you org to declare a variable using the var
‘eyword the variable wil work, but it wil be treated
_3 global variable this considered ba practice).
function getArea(width, hetoht)
var area = width * heights
1
|
5 wal Size
getarea
doce. wrt ve (wal
@ crosat score
FUNCTIONS, METHODS & OBJECTSHOW MEMORY &
VARIABLES WORK
Global variables use more memory. The browser has to remember them
for as long as the web page using them is loaded. Local variables are only
remembered during the period of time that a function is being executed.
CREATING THE VARIABLES IN CODE
Each variable that you declare takes up memory.
The moce variables a browser ha toremember,
the more memory your script equies to run.
‘Scripts that require alt of memory can perform
‘lower, which in turn makes your web page take
longer to respond tothe user.
var width = 15;
var height = 30;
var shall = trues
rar canPaint = trues
‘Avatable actually references avalue thai stored
in memory. The same value canbe used with more
‘than one variable
var width = 155
®
sa eat = 30;
var iskall = true;———>
var canPaint = true; > (¥
NAMING COLLISIONS
You might think you woud avoid naming colisions;
afterall you know which variables you ar using
But many ites use scrips written by several people.
Wan HTML page uses two JavaScript es, and both
have a global variable with the same name, it can
‘cause errors. Imagine 2 page using these two scripts
1/ Show size of the building plot
function shovPlotSize()(
var width = 3
var beight =
return "Ares:
)
var asg = showArea()
+ (width * etane)
U/ Show size of the arden
function showGardensize() {
var width = 125
var hetght = 25:
return width * heights
)
var ag = showardensize();
Here the values forthe width nd height ofthe wall
ae stored separately, but the same value of true
can be used for both isMal¥ and canPant.
© Varabes in function sape: there is no confit
between them,
beri arCOMNETEWHAT IS AN OBJECT?
ott :
Objects group together a set of variables and functions to create a model
of a something you would recognize from the real world. In an object,
variables and functions take on new names.
IN AN OBJECT: VARIABLES BECOME —_IN AN OBJECT: FUNCTIONS BECOME
KNOWN AS PROPERTIES. KNOWN AS METHODS
Wa varable is part ofan abject, tis ealed 3 Ia function's pat ofan object tis clled 2 method
property Properties tellus about the abject, such as Methods represent tasks that are associated with
the name hotel or the numberof rooms it has the object. For example, you can check how many
Each individual hotel might have afferent name rooms are avaiable by subtracting the numberof
anda diferent number of rooms bake rooms from the otal numberof roams.
FUNCTIONS, METHODS @ OBJECTSThis object represents a hotel. It has five properties and one method.
The object is in curly braces. It is stored in a variable called hotel.
Uke varisbles and ramed functions, An objectcannothavetwokeys The value ofa property can bea
properties and methodshavea —_withthesame name. Thisis string, number, Boolean aay oF
rnameand avaluc,Inan object, because lays areused to access even another object. The value of
that name scald a key, their corresponding values ‘method is always a function,
var hotel = {
(name: "Quay
(rooms: 40,
(booked: 25.
Coym:” true
LOPERTIES
cooeemnmnnn |" Theseare variables
roonfvpes? (win', "Obie",
checkAvailability: function() {
| return this.rooms - this.booked; | Menno
Hy E | Tisisa function
he
[Above you can see a hotel object. The object Programmers use alot of name/ ave pats
contains the folowing key/value pais (© HTMLuses attribute names and values.
© CSS uses property names and values.
PROPERTIES: KEY VALUE
ane string In Javaserit:
roons umber ‘© Variables have aname and you can assgn them a
booked number value of astring. number, of Boolean,
an Boolean ‘© Arrays have aname and a group of values. (Each
roonypes ary item in an array sa name/value pair because it
has an index number and a value.)
METHODS: checkAvailabsity function ‘© Named functions havea name and value that isa
setof statements to run the function is called
‘As youvwilseeoverthenext few page, thisisjst_ __-@ Objects consist ofa set of name/vaue pairs
‘one ofthe ways you can create an object. (but the names are referred toas keys).CREATING AN OBJECT:
LITERAL NOTATION
Tree Me ee ee ake ones
(There are several ways to create objects.)
The objects the cur E ed
— ee
checkAvailability: function’) {
return this.rooms - this.booked; : | memoo
ee ee ‘When setting properties treat the values ke you
et a eer)
cos coe
1 rumcrions, mernoosa omvecrsACCESSING AN OBJECT
AND DOT NOTATION
You access the properties or methods of an object using dot notation
Rent ees cn cee tr ces
To access.a property or method of abject youuse The periods known a the member operator. The
Coen ered ree pers ec a ere eer
Soa eee ear ecee ee Tey
Soeeee enter tried So eee erotica
= _
ON e290 LM
NCUA aa eee NOE AZ Ord
i
eee et oa
eS eee brackets and the property name sinsie them,
var hotelName = hotel['name'];
Sees
eee eee ear ee etch ey
Pe eter ner Seta nn eet te tee Ce
eee)CREATING OBJECTS USING
LITERAL NOTATION
This example starts by crating
anbject using itera notation, ca/sfabiect-itera 56 x
var hotel
ane: ‘Quay
rooms: 40,
booked: 25,
checkAvai lability: function() {
return this.roons - this.booked:
This objects called hoter which
var elName = docunent .getElenentiyld(*hotelNane!)
elNane.textContent = hotel nane;
var elRooms = docunent .getElenentayld( rooms") ;
elRoons.textContent = hotel .checkAvailability()s
followed by the method name.
hotel checkAvasability()
the method needs parameters
inthe
(2) Functions. wetHo0s a osvectsCREATING MORE
OBJECT LITERALS
EE cor/ijeseeritertais Here yoUsanste another objet
‘Againitiscalled hotel, but this
time the model represents 2
var hotel =
ane: ‘Park! itferent hal. For amoment,
rooms: 120,” Imagine that this is a diferent
booked: 77, page ofthe same travel webei
checkAvai lability: funetion() {
‘return this.rooms - this.bookeds Taw Pai abd loge tts:
120 rooms and 77 of hem are
booked.
‘The only things changing inthe
cade ae the values of the hot)
object's properties:
© The name of the hotel
{© How many rooms it has
(© How many rooms ae booked
var elNane = docunent.getElenentByld("hotelName");
celNane. textContent. = hotel .nanes
var elRoons = docunent .getElenentByld(*rooms"):
elRoons.textContent = hotel .checkAvatlability()s
The est ofthe pags works
act the same nay. The rare
shown sng he same code
Toe checebat ab f170
mnttod has ot choged ands
Ulead "s
sg += ''s
jisg += ‘chzohistory*s
@nsg += ‘"s
msg ++ ‘
gy|var el = document. gett lenent8y1¢(*info')s
el. innerHTML = msgs
@ alert( "current page: * + window. location):
4, Thewindow object's alert()
method is used to create a dialog
box shown on top ofthe page.
Its known 38 an alartbox
[though this is method ofthe
window abject, you may eet
used on its own (as shown here)
because the window objec is
treated as the default object it
none especies. (Historia,
the alere() method was used to
Aspley warings to users. These
days ther are better ways to
provide feedback)
FUNCTIONS, METHODS & OBJECTS ((THE DOCUMENT
OBJECT MODEL:
THE DOCUMENT OBJECT
The topmost object in the Document Object Model (or DOM) is the
document object. It represents the web page loaded into the current
browser window or tab. You meet its child objects in Chapter 5.
Here are some properties ofthe AS youwillsee in Chapter, the
ocurent object, whic ellyou_DOMlso creates an object for
about the current page ‘each lament onthe page.
PROPERTY DESCRIPTION
docunent title Tie of eurrent document
docunent .1asthodified Date on which document was last modifies
document URL Returns string containing URL ef current document
ocunent domain Returns domain of curent document
TheDOMisvitaltoaccessing _—Thetollowingare afew of the
and amendingthecontentsof methods that select content or
the curent web page Update the content ofa page.
METHOD DESCRIPTION
docunent.write()
document .getElenent8yid()
_that matches (ul description see 9195)
docunent..querySelectorAl() Retus ist of elements that match a CSS selector which is specified a6
‘parameter (ee 9202)
docunent.createtlement() Creates new element (see 9222)
document .createTextNode() _Createsrnew text node (see p222)
FUNCTIONS, METHODS & OBJECTS.USING THE DOCUMENT
OBJECT
This example gets information These deals arestoredinsde 2. Youhave seen the dacunent
about the page, andthen adds _avariable clledusg, along object's getClenentyle()
thet information to the footer ‘with HTML markup t spay tethodin several examples 0
‘the information. Again the r= far it selects an element from
4. The deals about the page are operator adds the new value the page using the value ofits
calleced from properties ofthe ontothe existing content ofthe _iattrbute. You wil ee this
ocunant object. sg variable method in more depth on p15,
EX 03/4s/docment-object.J6
var msg = ‘epochopage title: ! + document.title + ‘ " + docunent.URL + “ "s
msg += ‘last modified: ' + docuaent.lastModitied + ‘:
A gl i
el innerHTHL = msgs
$Seep228 for notes on using
“nmeriML because con be
asecunty rskiitis nt used
conrecty
The URL willook very diferent
ityourun this page local rather
than ona web server it il ely
begin ith F¥1e:/// rather than
swith etps/GLOBAL OBJECTS:
STRING OBJECT
Whenever you have a value that is a string, you can use the properties
and methods of the String object on that value. This example stores the
phrase "Home sweet home " in a variable.
var saying = ‘Home sweet home ';
These propertosandmethods -«sPROPERTY DESCRIPTION
ate often used to work with ext
eee isiex Returns number of charactersin the string
In most cases (see note baton ett)
‘onthe right-hand page, cote
Sonttcwoticneeetcnn) METHOD DESCRIPTION
blest er” petit) Guten damon
Succieeesissgag aaitaae() Conese
SNitsrenatesorebes) ayy) Tani sano ics
ranma. —— : Me nnn
within your script, and wrapper actin Returns index number ofthe lst ime a character or
object because it acts te 2 Tastindex0*() sot of characters found within the sting
seeeeacnhser Ratu chris tue nde
favre th hacer fet ax
‘object's properties and methods substring() umber is included and the character forthe last
‘onany value thats string index number is not includes
‘The Tength property counts When a character ie specified, spits the string
themumberof"code uits"ina split) each time ts found, then stores each indvival part
string: Inthe majority ofcases, —_amaray _ ee!
‘one character uses one code
nit and most programmersuse —trin() Removes whitespace rom start and end of string
‘tik his. ut some of the rarely rae oe
used characters take up two Like find and replace it takes one value that should
rode units replace() _betfound, and another to replace it (by default it only
replaces ithe frst matent tines)
@ roncrions, moos onueersEach character in a string is automatically given a number, called an index
number. Index numbers always start at zero and not one (just like for
items in an array).
Home sweet home
@oe0e0000000 o eoe
EXAMPLE esutt
sient ieee i
EXAMPLE - pesuit
ying. tolpercue(); Wane avaet howe
saying. toLovercese()s
saying chart (12);
saying. indexOf(‘ee");
saying-lastIndexOf(*e"
saying substring (8,14) 5
Wome sweet home
Home sweet
sweet home
di
© sweet home
Home
sweet home
‘home sweet hone '
HOME SWEET HOME *
saying.trin()s
Home sweet home
Home sweet hone
"); Home sweet howe
tone’, ‘sweet, ‘hone! *]
"Home sweet home"
runcrions,mernoos«onveers (3)WORKING WITH STRINGS
This example demonstrates the 2. The next nels youhow The name ofthe variable
Tenath poperty and many ofthe manycharacters are inthe sting (saying) followed by a dt,
string object's methods shown _usingthe length property ofthe then the property or method that
onthe previous page String abject and stoves the isbeing demonstrated Gn the
resultina varisbe called msg, ‘same way thatthe other objects
This example starts by storing 3. Theis followed by examples _inthis chapter used the dot
the phrase Hone sweet hane ” showing severaof he String notion oindicatea property or
inavariabe called saying. object's methods ‘method of an obec
@ var saying = ‘Hone sweet hone *s
@® var msg = 'length ' + saying. length +
"
[insg += ‘uppercase ' + saying.toUppertase() +
|nsg += "lovercase' + saying.toLowerCase() + '
"
insg += ‘character index: 12' + saying.charat(12) + "
";
@jnsg += 'first ees/h2>' + saying. indexO#(ee!) + "
"
is += “chd>last e" + saying. lastIndexOf("e") + *=/p>'s
fee's
Insg #= ‘character index: 8-14" + saying.substring(8, 14) + ‘
's
insg += ‘chd>replacec/h2>' + saying.replace('me', ‘w') + ‘
@Iver 1 = docunent.getEenentyia(*info')s
fnneriTNL = msgs
4. The ral two ines select the
‘lement with an f¢ atribute
‘whose values nfo ad then
4 the value ofthe mag variable
inside that element
(Remember, security issues with
sing the fanerfM. property
are discussed on p28)
(30) FUNCTIONS, METHODS @ OBJECTSDATA TYPES REVISITED
In JavaScript there are six data type:
Five of them are described as simple (or primitive) data types.
The sixth is the object (and is referred to as a complex data type).
SIMPLE OR PRIMITIVE DATA TYPES
avaScrip has fv simple or primitive) data types:
1. String
2.Number
Boolean
4.Undefined a variable that hasbeen declared, but
no valuehas been assigned tot yet)
‘5. Null (a varabl with no value ~itmay have had
‘one at some pont, but no longer has value)
‘As youhave seen bth the web browser and the
Current document canbe modeled using objects
(and objects can have methods and properties).
Butt canbe confusing to discover thata simple
‘vale (ikea string, a umber, 2 Boolean) can have
‘methods and properties, Under the hood, JavaScriot
tueas every variable as an object ints own ig
‘String: fa varisble or he property ofan obec,
contain string ou can use the properties and
methods ofthe String object ont
Number: I variable, or property ofan object.
storesa number; you can use the properties and
methods of the Rinber object onit See next page)
Boolean: Thee is 3 Boolean abject. tis rarely used,
Undefined and mal valves donot have objects)
COMPLEX DATA TYPE
JavaScript also defines a complox data type:
6.Object
Under the hood, arrays and functions are considered
types of objects
ARRAYS ARE OBJECTS
‘Asyousaw on pS, anarrayisa st of key/value
airs Gustlke anyother object. But you dont
spect the name inthe key/value par of an atray it
isanindes number
Like other objects, arrays have properties and
‘methods. On p72 yousaw that arrays havea
property called Tenth, which tls youhow many
itemsare inthataray. There sao a set of methods
youcan use with any array to add ites tot remove
items omit, or reorder its contents. You wll mect
those methods in Chapter 12
FUNCTIONS ARE OBJECTS
Technically, functions are ato objects. But they
have an addtional feature: they are calable, which
‘means you can tol the interpreter when you want to
execute the statements that it containsGLOBAL OBJECTS:
NUMBER OBJECT
Whenever you have a value that is a number,
you can use the methods and properties of the
Number object on it.
These methods ae helpful ‘Many calculations involving, (rin an animation, you might
when dealing with range of currency (uch a taxrates) wil waht to specty that certain
applications from financial need tobe rounded oaspecic elements should be evenly
calculations te animations numberof decimal places. spaced out across the page
METHOD DESCRIPTION
‘san ‘Chocks the valu is not a number
toFixed() Rounds to spectied number of decimal places (returns 2 tring)
toPrecision() Rounds to total number of places turns a string)
to€xponential () etuensa string representing the number n exponential notation
COMMONLY USED TERMS:
{© Anintegeris 2 wholenumber (nat a fraction.
{© Areal numbers 2 number that ean containa fractional part.
{© A floating point number 3 real umber that uses decimals to repcesent fraction. The term footing point
relers othe decimal point
1 Scientific notations a ay of miting numbers that are to big or too smal to be convenient witen in
a youuu oud) tod
instead of the floor() method,
‘Remumber end woud
faces etc
puter ttn hat 29 woud
tae
CUM
Anything between 15 and1999
would get rounded upto 2, and
Anything between 9 and 9:5
would be rounded down to 9.
Using the aor() method
ensures that the numbers
alwaysrounded down tothe
nearest integer, and youcan
then add to ensure the number
isbetween ana".
FUNCTIONS, METHODS & OBJECTS ({55)CREATING AN INSTANCE
OF THE DATE OBJECT
In order to work with dates, you create an instance of the Date object.
You can then specify the time and date that you want it to represent.
——
NLM ACTON] a Date();
aT:
ae as
SreeGLOBAL OBJECTS:
DATE OBJECT (AND TIME)
Once you have created a Date object, the following methods let you set
and retrieve the time and date that it represents.
METHOD DESCRIPTION
‘etDate() setoate() Returns / sets the day ofthe month (31)
getday() the day ofthe
getrultvear() Rtrns ets the yar gt)
gettours() settiours() Retuns sets the hour (0-23) _
getMiTTiseconds() __setWiTl4seconds() Returns /setstherilieconds ©-999)
getminutes()_ __settimutes() —__Retuns/ sets the minutes (0-59) .
getMorth() Returns / sets the month (0-1)
getseconds(
getTine() (00:00:00 UTC (Coordinated Universal Time)
and a negative number fr ary time before
getTinezone0ffset() Returns time zone offset in mins or locale
tobatestring() Returns “date” asa human-readable string
‘toTinestring()
tostring() Returns a srng representing the specified cate
“The toatestring() method toTimeString() showsthetime. The Date object does not store
willdspay te date the Several programming languages thenames of days or months as
following format: speciy dates in miliseconds they vary between languages
Wed Apr 16 1575 since midriht on Jan 1970
This known a5 Uris time, Instead ituses a number rom
you waot to play the date in 0 to6 forthe days of the week
‘another way,you'can construct Aviitorslocaton mayatflect and Oto forthe months.
‘aiferent dat format usingthe time zones andlanguage spoken
individual methods sted above Programmers use the term Toshow theirnames, you need
torepresentthe inivdsalparts_localetorefertothisknd of to create anaraytohold them
day date, month, year location-based information Gee p43)CREATING A DATE OBJECT
1Linthis example, anew Dave yu do not speciy a date (Once you have an Instance ofthe
objects created using the when creating aDateobject,it —_Dateobject (holding the current
Date() obyect constructor willcontain the date ar time date and time). you can use any
itis caled today when the JavaScript interpreter oft properties or methods.
encounters that ine of code
@ var today = new dates
@® var year = today getFul Vear()s
fit ci tooment set ements footer’)
el-innerHTML = 'Copyright Bcopys' + year + ‘
2. Inthis example, you can see
that getFullYear() isused to
‘etuenthe yea ofthe date beng
stored inthe Date cbect,
3. Inthis case itis beng used
‘townie the cient year ina
copyright statement.
(sa) TIONS, METHODS & OBJECTS:
(68) Functions, iWORKING WITH
DATES & TIMES
Tospecitya dateand ime, you. The etderand syntax for this is! Another way to format the date
can se this format: Year fourcigits and time se this
Month 0-11 Uanis)
YYYE, mM, D, My IH, SS Day Lat or 00, YY Hasotss
1996, 08, 16, 15, 45, 55 Hou 0-23, Apr 16, 1996 15:45:55
Minutes 0-59,
This represents 34S5pm and55. Seconds 0-59 You can omit the time portion i
seconds on April 16,1996, Miliseconds 0-999 you donot noed it
ENING 03/)/aatecobject- ferences
‘var today = new Date();
var year = today.getFul 1vear();
var est = new Date(‘Apr 16, 1996 15:45:55")
@® var difference = today.getTine() - est.cetTine();
© sifference » (difference / 31556900000) ;
var eINsg = docunent.getElenent8yld('mossage")
elMsg.textContent = Nath.floor(difference) + * years of online travel advice's
{Lin this example, you can see a
date being etn tho pas
2. Ifyou ty tofind the ference
between two dates, you wll end
wp with result inmilisconds,
3. Togetthediference in
a a 3 ays/weeks/years, you divide
this number by the numberof
milseconds ina day/meek/ yea.
Here the number is livided by
31556 900,000 - the umber
of miliseconds ina year hat is
not aleap yea).
FUNCTIONS, METHODS & OBJECTS ((89)EXAMPLE
FUNCTIONS,
METHODS & OBJECTS
This example is split into two parts. The first
shows you the details about the hotel, room
rate, and offer rate. The second part indicates,
when the offer expires
Allo the codes placed inside an immediatly invoked function
‘expression (FE) to ensure any variable names usedin the script do not
‘ash wth variable names used nother scrips,
The frst part ofthe scrip creates hotel object ithastvee properties
(hehotelname room rat, and percentage discount being offered), plus
2 method to calculate the offer pice whichis shown to the use,
The details ofthe discount are writen ito the page using information|
‘om this hate! object. To eneure thatthe discounted ates shown with
two decimal places (like most prices ae shown) the .toFxed() method
of hetlunber object isused
“The second part ofthe serpt shows thatthe offer willexpie in seven
ays. Goes ths using a function called offerExpires(). The date
currently set onthe user's computer is passed as an argument othe
tfferExpires() functions that can calculate when the offer ends
Inside the function, anew Date objec i created and seven daysis.
‘added to today’s date. The Date object represents the days and months
‘as numbers (tating at 0) soto show the name of the day and monty ~
‘wo araye ae coated storing all possible day and month names. When
the message s written, itretrieves the appropriate day/month fom
those anys
“Themessage to show the expiry date is bil up inside a variable called
expiryteg. The code that cals the of erExpires() function and
displays the messageis at the end of the sript selects the element
were the message should appear and updates its content using the
AnerHTAL property, which you wll mest in Chapter.
FUNCTIONS, METHODS 2 OBJECTS (