9/30/2015
Values,Types,andOperators::EloquentJavaScript
Chapter 1
Values, Types, and Operators
Belowthesurfaceofthemachine,[Link],itexpandsand
[Link],[Link]
[Link].
MasterYuanMa,TheBookofProgramming
Insidethecomputersworld,[Link],modifydata,
[Link]
isstoredaslongsequencesofbitsandisthusfundamentallyalike.
Bitsareanykindoftwovaluedthings,usuallydescribedaszerosandones.
Insidethecomputer,theytakeformssuchasahighorlowelectricalcharge,a
strongorweaksignal,[Link]
ofdiscreteinformationcanbereducedtoasequenceofzerosandonesand
thusrepresentedinbits.
Forexample,[Link]
thesamewayyouwritedecimalnumbers,butinsteadof10differentdigits,you
haveonly2,andtheweightofeachincreasesbyafactorof2fromrighttoleft.
Herearethebitsthatmakeupthenumber13,withtheweightsofthedigits
shownbelowthem:
0
128
0
64
0
32
0
16
1
8
1
4
0
2
1
1
Sothatsthebinarynumber00001101,or8+4+1,whichequals13.
Values
[Link]
[Link](thehard
diskorequivalent)tendstohaveyetafewordersofmagnitudemore.
[Link]
1/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
Tobeabletoworkwithsuchquantitiesofbitswithoutgettinglost,youcan
[Link]
environment,[Link]
bits,[Link].
TherearesixbasictypesofvaluesinJavaScript:numbers,strings,Booleans,
objects,functions,andundefinedvalues.
Tocreateavalue,[Link]
[Link]
callforone,andwoosh,[Link],of
[Link],andifyouwanttousea
giganticamountofthematthesametime,youmightrunoutofbits.
Fortunately,[Link]
soonasyounolongeruseavalue,itwilldissipate,leavingbehinditsbitstobe
recycledasbuildingmaterialforthenextgenerationofvalues.
ThischapterintroducestheatomicelementsofJavaScriptprograms,thatis,
thesimplevaluetypesandtheoperatorsthatcanactonsuchvalues.
Numbers
Valuesofthenumbertypeare,unsurprisingly,[Link]
program,theyarewrittenasfollows:
13
[Link]
2/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
Usethatinaprogram,anditwillcausethebitpatternforthenumber13to
comeintoexistenceinsidethecomputersmemory.
JavaScriptusesafixednumberofbits,namely64ofthem,tostoreasingle
numbervalue.Thereareonlysomanypatternsyoucanmakewith64bits,
whichmeansthattheamountofdifferentnumbersthatcanberepresentedis
[Link],theamountofnumbersthatcanberepresented
[Link],given64binarydigits,youcanrepresent264different
numbers,whichisabout18quintillion(an18with18zerosafterit).Thisisa
lot.
Computermemoryusedtobealotsmaller,andpeopletendedtousegroupsof
[Link]
suchsmallnumberstoendupwithanumberthatdidnotfitintothegiven
[Link],evenpersonalcomputershaveplentyofmemory,soyou
arefreetouse64bitchunks,whichmeansyouneedtoworryaboutoverflow
onlywhendealingwithtrulyastronomicalnumbers.
Notallwholenumbersbelow18quintillionfitinaJavaScriptnumber,though.
Thosebitsalsostorenegativenumbers,soonebitindicatesthesignofthe
[Link]
dothis,[Link]
actualmaximumwholenumberthatcanbestoredismoreintherangeof9
quadrillion(15zeros),whichisstillpleasantlyhuge.
Fractionalnumbersarewrittenbyusingadot.
9.81
Forverybigorverysmallnumbers,youcanalsousescientificnotationby
addingane(forexponent),followedbytheexponentofthenumber:
2.998e8
[Link]
3/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
Thatis2.998108=299,800,000.
Calculationswithwholenumbers(alsocalledintegers)smallerthanthe
aforementioned9quadrillionareguaranteedtoalwaysbeprecise.
Unfortunately,[Link]
(pi)cannotbepreciselyexpressedbyafinitenumberofdecimaldigits,many
numberslosesomeprecisionwhenonly64bitsareavailabletostorethem.
Thisisashame,[Link]
importantthingistobeawareofitandtreatfractionaldigitalnumbersas
approximations,notasprecisevalues.
A rit h met ic
[Link]
asadditionormultiplicationtaketwonumbervaluesandproduceanew
[Link]:
100 + 4 * 11
The + and * [Link],and
[Link]
willapplyittothosevaluesandproduceanewvalue.
Doestheexamplemeanadd4and100,andmultiplytheresultby11,oristhe
multiplicationdonebeforetheadding?Asyoumighthaveguessed,the
[Link],youcanchangethisby
wrappingtheadditioninparentheses.
(100 + 4) * 11
Forsubtraction,thereisthe - operator,anddivisioncanbedonewiththe /
operator.
Whenoperatorsappeartogetherwithoutparentheses,theorderinwhichthey
[Link]
[Link]
4/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
[Link] / operatorhasthesame
precedenceas * .Likewisefor + and - .Whenmultipleoperatorswiththesame
precedenceappearnexttoeachother,asin 1 - 2 + 1 ,theyareappliedleftto
right: (1 - 2) + 1 .
[Link]
doubt,justaddparentheses.
Thereisonemorearithmeticoperator,whichyoumightnotimmediately
[Link] % symbolisusedtorepresenttheremainderoperation. X % Y
istheremainderofdividing X by Y .Forexample, 314 % 100 produces 14 ,
and 144 % 12 gives 0 .Remaindersprecedenceisthesameasthatof
[Link]
modulo,thoughtechnicallyremainderismoreaccurate.
S p e c i al nu m b e r s
TherearethreespecialvaluesinJavaScriptthatareconsiderednumbersbut
dontbehavelikenormalnumbers.
Thefirsttwoare Infinity and -Infinity ,whichrepresentthepositiveand
negativeinfinities. Infinity - 1 isstill Infinity ,[Link]
[Link],andit
willquicklyleadtoournextspecialnumber: NaN .
NaN standsfornotanumber,eventhoughitisavalueofthenumbertype.
Youllgetthisresultwhenyou,forexample,trytocalculate 0 / 0 (zero
dividedbyzero), Infinity - Infinity ,oranynumberofothernumeric
operationsthatdontyieldaprecise,meaningfulresult.
Strings
[Link]
arewrittenbyenclosingtheircontentinquotes.
[Link]
5/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
"Patch my boat with chewing gum"
'Monkeys wave goodbye'
Bothsingleanddoublequotescanbeusedtomarkstringsaslongasthequotes
atthestartandtheendofthestringmatch.
Almostanythingcanbeputbetweenquotes,andJavaScriptwillmakeastring
[Link]
[Link](thecharactersyouget
whenyoupressEnter)[Link]
onasingleline.
Tomakeitpossibletoincludesuchcharactersinastring,thefollowing
notationisused:wheneverabackslash( \ )isfoundinsidequotedtext,it
[Link]
[Link]
[Link] n characteroccursafterabackslash,itis
[Link],a t afterabackslashmeansatabcharacter.
Takethefollowingstring:
"This is the first line\nAnd this is the second"
Theactualtextcontainedisthis:
This is the first line
And this is the second
Thereare,ofcourse,situationswhereyouwantabackslashinastringtobe
justabackslash,[Link],they
willcollapsetogether,andonlyonewillbeleftintheresultingstringvalue.
Thisishowthestring A newline character is written like "\n". can
beexpressed:
"A newline character is written like \"\\n\"."
[Link]
6/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
Stringscannotbedivided,multiplied,orsubtracted,butthe + operatorcanbe
[Link],butitconcatenatesitgluestwostrings
[Link] "concatenate" :
"con" + "cat" + "e" + "nate"
Therearemorewaysofmanipulatingstrings,whichwewilldiscusswhenwe
gettomethodsinChapter4.
Unary operators
[Link]
typeof operator,whichproducesastringvaluenamingthetypeofthevalue
yougiveit.
[Link](typeof 4.5)
// number
[Link](typeof "x")
// string
edit&runcodebyclickingit
Wewilluse [Link] inexamplecodetoindicatethatwewanttoseethe
[Link],thevalueproduced
shouldbeshownonthescreen,thoughhowitappearswilldependonthe
JavaScriptenvironmentyouusetorunit.
Theotheroperatorswesawalloperatedontwovalues,but typeof takesonly
[Link],whilethosethat
[Link]
binaryoperatorandasaunaryoperator.
[Link](- (10 - 2))
// -8
Boolean values
Often,youwillneedavaluethatsimplydistinguishesbetweentwopossibilities,
[Link]
7/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
[Link],JavaScripthasaBooleantype,
whichhasjusttwovalues:trueandfalse(whicharewrittensimplyasthose
words).
Co mp a ri son s
HereisonewaytoproduceBooleanvalues:
[Link](3 > 2)
// true
[Link](3 < 2)
// false
The > and < signsarethetraditionalsymbolsforisgreaterthanandisless
than,[Link]
Booleanvaluethatindicateswhethertheyholdtrueinthiscase.
Stringscanbecomparedinthesameway.
[Link]("Aardvark" < "Zoroaster")
// true
Thewaystringsareorderedismoreorlessalphabetic:uppercaselettersare
alwayslessthanlowercaseones,so "Z" < "a" istrue,andnonalphabetic
characters(!,,andsoon)[Link]
[Link]
tovirtuallyeverycharacteryouwouldeverneed,includingcharactersfrom
Greek,Arabic,Japanese,Tamil,[Link]
storingstringsinsideacomputerbecauseitmakesitpossibletorepresent
[Link],JavaScriptgoesover
themfromlefttoright,comparingthenumericcodesofthecharactersoneby
one.
Othersimilaroperatorsare >= (greaterthanorequalto), <= (lessthanor
equalto), == (equalto),and != (notequalto).
[Link]
8/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
[Link]("Itchy" != "Scratchy")
// true
ThereisonlyonevalueinJavaScriptthatisnotequaltoitself,andthatis NaN ,
whichstandsfornotanumber.
[Link](NaN == NaN)
// false
NaN issupposedtodenotetheresultofanonsensicalcomputation,andas
such,itisntequaltotheresultofanyothernonsensicalcomputations.
L og ic a l op e r a tor s
TherearealsosomeoperationsthatcanbeappliedtoBooleanvalues
[Link]:and,or,andnot.
ThesecanbeusedtoreasonaboutBooleans.
The && [Link],anditsresultis
trueonlyifboththevaluesgiventoitaretrue.
[Link](true && false)
// false
[Link](true && true)
// true
The || [Link]
toitistrue.
[Link](false || true)
// true
[Link](false || false)
// false
Notiswrittenasanexclamationmark( ! ).Itisaunaryoperatorthatflipsthe
valuegiventoit !true produces false and !false gives true .
[Link]
9/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
WhenmixingtheseBooleanoperatorswitharithmeticandotheroperators,itis
[Link],youcanusually
getbywithknowingthatoftheoperatorswehaveseensofar, || hasthe
lowestprecedence,thencomes && ,thenthecomparisonoperators( > , == ,and
soon),[Link],intypical
expressionslikethefollowingone,asfewparenthesesaspossibleare
necessary:
1 + 1 == 2 && 10 * 10 > 50
ThelastlogicaloperatorIwilldiscussisnotunary,notbinary,butternary,
[Link],like
this:
[Link](true ? 1 : 2);
// 1
[Link](false ? 1 : 2);
// 2
Thisoneiscalledtheconditionaloperator(orsometimesjustternaryoperator
sinceitistheonlysuchoperatorinthelanguage).Thevalueontheleftofthe
[Link]
true,themiddlevalueischosen,andwhenitisfalse,thevalueontheright
comesout.
Undefined values
Therearetwospecialvalues,written null and undefined ,thatareusedto
[Link],butthey
carrynoinformation.
Manyoperationsinthelanguagethatdontproduceameaningfulvalue(youll
seesomelater)yield undefined simplybecausetheyhavetoyieldsomevalue.
Thedifferenceinmeaningbetween undefined and null isanaccidentof
[Link]
10/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
JavaScriptsdesign,[Link]
youactuallyhavetoconcernyourselfwiththesevalues,Irecommendtreating
themasinterchangeable(moreonthatinamoment).
Automatic type conversion
Intheintroduction,ImentionedthatJavaScriptgoesoutofitswaytoaccept
almostanyprogramyougiveit,[Link]
nicelydemonstratedbythefollowingexpressions:
[Link](8 * null)
// 0
[Link]("5" - 1)
// 4
[Link]("5" + 1)
// 51
[Link]("five" * 2)
// NaN
[Link](false == 0)
// true
Whenanoperatorisappliedtothewrongtypeofvalue,JavaScriptwill
quietlyconvertthatvaluetothetypeitwants,usingasetofrulesthatoften
[Link] null inthe
firstexpressionbecomes 0 ,andthe "5" inthesecondexpressionbecomes 5
(fromstringtonumber).Yetinthethirdexpression, + triesstring
concatenationbeforenumericaddition,sothe 1 isconvertedto "1" (from
numbertostring).
Whensomethingthatdoesntmaptoanumberinanobviousway(suchas
"five" or undefined )isconvertedtoanumber,thevalue NaN isproduced.
Furtherarithmeticoperationson NaN keepproducing NaN ,soifyoufind
yourselfgettingoneofthoseinanunexpectedplace,lookforaccidentaltype
conversions.
Whencomparingvaluesofthesametypeusing == ,theoutcomeiseasyto
[Link]
11/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
predict:youshouldgettruewhenbothvaluesarethesame,exceptinthecase
of NaN .Butwhenthetypesdiffer,JavaScriptusesacomplicatedandconfusing
[Link],itjusttriestoconvertoneof
[Link],when null or undefined occurs
oneithersideoftheoperator,itproducestrueonlyifbothsidesareoneof
null or undefined .
[Link](null == undefined);
// true
[Link](null == 0);
// false
[Link]
valuehasarealvalueinsteadof null or undefined ,youcansimplycompare
itto null withthe == (or != )operator.
Butwhatifyouwanttotestwhethersomethingreferstotheprecisevalue
false ?TherulesforconvertingstringsandnumberstoBooleanvaluesstate
that 0 , NaN ,andtheemptystring( "" )countas false ,whilealltheother
valuescountas true .Becauseofthis,expressionslike 0 == false and "" ==
false [Link],whereyoudonotwantanyautomatic
typeconversionstohappen,therearetwoextraoperators: === and !== .The
firsttestswhetheravalueispreciselyequaltotheother,andthesecondtests
[Link] "" === false isfalseasexpected.
Irecommendusingthethreecharactercomparisonoperatorsdefensivelyto
[Link]
certainthetypesonbothsideswillbethesame,thereisnoproblemwithusing
theshorteroperators.
S h o r t - c ir c u iti n g o f l ogic al o per ator s
Thelogicaloperators && and || handlevaluesofdifferenttypesinapeculiar
[Link]
decidewhattodo,butdependingontheoperatorandtheresultofthat
[Link]
12/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
conversion,theyreturneithertheoriginallefthandvalueortherighthand
value.
The || operator,forexample,willreturnthevaluetoitsleftwhenthatcanbe
[Link]
conversionworksasyoudexpectforBooleanvaluesandshoulddosomething
analogousforvaluesofothertypes.
[Link](null || "user")
// user
[Link]("Karl" || "user")
// Karl
Thisfunctionalityallowsthe || operatortobeusedasawaytofallbackona
[Link]
theleft,thevalueontherightwillbeusedasareplacementinthatcase.
The && operatorworkssimilarly,[Link]
itsleftissomethingthatconvertstofalse,itreturnsthatvalue,andotherwiseit
returnsthevalueonitsright.
Anotherimportantpropertyofthesetwooperatorsisthattheexpressionto
[Link] true || X ,no
matterwhat X isevenifitsanexpressionthatdoessomethingterriblethe
resultwillbetrue,and X [Link] false && X ,
whichisfalseandwillignore X .Thisiscalledshortcircuitevaluation.
[Link]
evaluated,butthesecondorthirdvalue,theonethatisnotpicked,isnot.
Summary
WelookedatfourtypesofJavaScriptvaluesinthischapter:numbers,strings,
Booleans,andundefinedvalues.
Suchvaluesarecreatedbytypingintheirname( true , null )orvalue( 13 ,
[Link]
13/14
9/30/2015
Values,Types,andOperators::EloquentJavaScript
"abc" ).[Link]
operatorsforarithmetic( + , - , * , / ,and % ),stringconcatenation( + ),
comparison( == , != , === , !== , < , > , <= , >= ),andlogic( && , || ),aswellas
severalunaryoperators( - tonegateanumber, ! tonegatelogically,and
typeof tofindavaluestype)andaternaryoperator( ?: )topickoneoftwo
valuesbasedonathirdvalue.
ThisgivesyouenoughinformationtouseJavaScriptasapocketcalculator,but
[Link]
intobasicprograms.
[Link]
14/14