With this book you will: ■ Learn the essential programming building blocks, including operators, types, variables, conditionals, loops, and functions ■ Become familiar with JavaScript’s
Trang 1“When you strive to comprehend your code, you create better work and become better at what you do The code isn’t just your job anymore, it’s your craft This is why I love Up & Going.”
—JENN LUKAS, Frontend consultant
It’s easy to learn parts of JavaScript, but much harder to learn it completely—or even
sufficiently—whether you’re new to the language or have used it for years With the “You Don’t
Know JS” book series, you’ll get a more complete understanding of JavaScript, including trickier
parts of the language that many experienced JavaScript programmers simply avoid
The series’ first book, Up & Going, provides the necessary background for those of you with
limited programming experience By learning the basic building blocks of programming, as
well as JavaScript’s core mechanisms, you’ll be prepared to dive into the other, more in-depth
books in the series—and be well on your way toward true JavaScript
With this book you will:
■ Learn the essential programming building blocks, including operators, types,
variables, conditionals, loops, and functions
■ Become familiar with JavaScript’s core mechanisms, such as values, function
closures, this, and prototypes
■ Get an overview of other books in the series—and learn why it’s important to
understand all parts of JavaScript
Kyle Simpson is an Open Web evangelist from Austin, TX, who’s passionate about all things JavaScript
He’s an author, workshop trainer, tech speaker, and OSS contributor/leader
oreilly.comYouDontKnowJS.com
The YOU DON’T KNOW JS series includes:
■ Up & Going
■ Scope & Closures
■ this & Object Prototypes
■ Types & Grammar
■ Async & Performance
■ ES6 & Beyond
ISBN: 978-1-491-92446-4
JAVASCRIPT
Trang 2“When you strive to comprehend your code, you create better work and become better at what you do The code isn’t just your job anymore, it’s your craft This is why I love Up & Going.”
—JENN LUKAS, Frontend consultant
It’s easy to learn parts of JavaScript, but much harder to learn it completely—or even
sufficiently—whether you’re new to the language or have used it for years With the “You Don’t
Know JS” book series, you’ll get a more complete understanding of JavaScript, including trickier
parts of the language that many experienced JavaScript programmers simply avoid
The series’ first book, Up & Going, provides the necessary background for those of you with
limited programming experience By learning the basic building blocks of programming, as
well as JavaScript’s core mechanisms, you’ll be prepared to dive into the other, more in-depth
books in the series—and be well on your way toward true JavaScript
With this book you will:
■ Learn the essential programming building blocks, including operators, types,
variables, conditionals, loops, and functions
■ Become familiar with JavaScript’s core mechanisms, such as values, function
closures, this, and prototypes
■ Get an overview of other books in the series—and learn why it’s important to
understand all parts of JavaScript
Kyle Simpson is an Open Web Evangelist from Austin, TX, who’s passionate about all things JavaScript
He’s an author, workshop trainer, tech speaker, and OSS contributor/leader
The YOU DON’T KNOW JS series includes:
■ Up & Going
■ Scope & Closures
■ this & Object Prototypes
■ Types & Grammar
■ Async & Performance
■ ES6 & Beyond
ISBN: 978-1-491-92446-4
JAVASCRIPT
Trang 3Kyle Simpson
Up & Going
Trang 4[LSI]
Up & Going
by Kyle Simpson
Copyright © 2015 Getify Solutions All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://safaribooksonline.com) For more information, contact our corporate/institutional sales department:
800-998-9938 or corporate@oreilly.com.
Editors: Simon St.Laurent and Brian
MacDonald
Production Editor: Kristen Brown
Copyeditor: Jasmine Kwityn
Proofreader: Amanda Kersey
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Rebecca Demarest April 2015: First Edition
Revision History for the First Edition
2015-03-17: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781491924464 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc You Don’t Know JS: Up & Going, the cover image, and related trade dress are trademarks of O’Reilly
Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limi‐ tation responsibility for damages resulting from the use of or reliance on this work Use of the information and instructions contained in this work is at your own risk If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsi‐ bility to ensure that your use thereof complies with such licenses and/or rights.
Trang 5Table of Contents
Foreword v
Preface vii
1 Into Programming 1
Code 2
Expressions 3
Try It Yourself 4
Operators 8
Values & Types 10
Code Comments 12
Variables 14
Blocks 17
Conditionals 18
Loops 20
Functions 22
Practice 26
Review 28
2 Into JavaScript 29
Values & Types 30
Variables 40
Conditionals 43
Strict Mode 45
Functions as Values 47
this Identifier 52
Prototypes 53
iii
Trang 6Old & New 55
Non-JavaScript 58
Review 59
3 Into YDKJS 61
Scope & Closures 61
this & Object Prototypes 62
Types & Grammar 63
Async & Performance 64
ES6 & Beyond 65
Review 67
A Acknowledgments 69
Trang 7What was the last new thing you learned?
Perhaps it was a foreign language, like Italian or German Or maybe
it was a graphics editor, like Photoshop Or a cooking technique orwoodworking or an exercise routine I want you to remember thatfeeling when you finally got it: the lightbulb moment When thingswent from blurry to crystal clear, as you mastered the table saw orunderstood the difference between masculine and feminine nouns
in French How did it feel? Pretty amazing, right?
Now I want you to travel back a little bit further in your memory to
right before you learned your new skill How did that feel? Probably
slightly intimidating and maybe a little bit frustrating, right? At onepoint, we all did not know the things that we know now, and that’stotally OK; we all start somewhere Learning new material is anexciting adventure, especially if you are looking to learn the subjectefficiently
I teach a lot of beginner coding classes The students who take myclasses have often tried teaching themselves subjects like HTML orJavaScript by reading blog posts or copying and pasting code, butthey haven’t been able to truly master the material that will allowthem to code their desired outcome And because they don’t trulygrasp the ins and outs of certain coding topics, they can’t write pow‐erful code or debug their own work because they don’t really under‐stand what is happening
I always believe in teaching my classes the proper way, meaning Iteach web standards, semantic markup, well-commented code, andother best practices I cover the subject in a thorough manner toexplain the hows and whys, without just tossing out code to copy
v
Trang 8and paste When you strive to comprehend your code, you createbetter work and become better at what you do The code isn’t just
your job anymore, it’s your craft This is why I love Up & Going Kyle
takes us on a deep dive through syntax and terminology to give agreat introduction to JavaScript without cutting corners This bookdoesn’t skim over the surface but really allows us to genuinelyunderstand the concepts
Because it’s not enough to be able to duplicate jQuery snippets intoyour website, the same way it’s not enough to learn how to open,close, and save a document in Photoshop Sure, once I learned a fewbasics about the program, I could create and share a design I made.But without legitimately knowing the tools and what is behindthem, how can I define a grid, or craft a legible type system, or opti‐mize graphics for web use The same goes for JavaScript Withoutknowing how loops work, or how to define variables, or what scope
is, we won’t be writing the best code we can We don’t want to settlefor anything less—this is, after all, our craft
The more you are exposed to JavaScript, the clearer it becomes.Words like closures, objects, and methods might seem out of reach
to you now, but this book will help those terms come into clarity Iwant you to keep those two feelings of before and after you learnsomething in mind as you begin this book It might seem daunting,but you’ve picked up this book because you are starting an awesome
journey to hone your knowledge Up & Going is the start of our path
to understanding programming Enjoy the lightbulb moments!
—Jenn Lukas ( http://jennlukas.com , @jennlukas),
Frontend consultant
Trang 9I’m sure you noticed, but “JS” in the series title is not an abbrevia‐tion for words used to curse about JavaScript, though cursing at thelanguage’s quirks is something we can probably all identify with!From the earliest days of the Web, JavaScript has been a founda‐tional technology that drives interactive experience around the con‐tent we consume While flickering mouse trails and annoying pop-
up prompts may be where JavaScript started, nearly two decadeslater, the technology and capability of JavaScript has grown manyorders of magnitude, and few doubt its importance at the heart ofthe world’s most widely available software platform: the Web.But as a language, it has perpetually been a target for a great deal ofcriticism, owing partly to its heritage but even more to its designphilosophy Even the name evokes, as Brendan Eich once put it,
“dumb kid brother” status next to its more mature older brother,Java But the name is merely an accident of politics and marketing.The two languages are vastly different in many important ways
“JavaScript” is as related to “Java” as “Carnival” is to “Car.”
Because JavaScript borrows concepts and syntax idioms from sev‐eral languages, including proud C-style procedural roots as well assubtle, less obvious Scheme/Lisp-style functional roots, it is exceed‐ingly approachable to a broad audience of developers, even thosewith little to no programming experience The “Hello World” ofJavaScript is so simple that the language is inviting and easy to getcomfortable with in early exposure
While JavaScript is perhaps one of the easiest languages to get upand running with, its eccentricities make solid mastery of the lan‐guage a vastly less common occurrence than in many other lan‐
vii
Trang 10guages Where it takes a pretty in-depth knowledge of a languagelike C or C++ to write a full-scale program, full-scale productionJavaScript can, and often does, barely scratch the surface of what thelanguage can do.
Sophisticated concepts that are deeply rooted into the language tend
instead to surface themselves in seemingly simplistic ways, such as
passing around functions as callbacks, which encourages the Java‐Script developer to just use the language as is and not worry toomuch about what’s going on under the hood
It is simultaneously a simple, easy-to-use language that has broadappeal, and a complex and nuanced collection of language mechan‐
ics that without careful study will elude true understanding even for
the most seasoned of JavaScript developers
Therein lies the paradox of JavaScript, the Achilles’ heel of the lan‐guage, the challenge we are presently addressing Because JavaScript
can be used without understanding, the understanding of the lan‐
guage is often never attained
Mission
If at every point that you encounter a surprise or frustration in Java‐Script, your response is to add it to the blacklist (as some are accus‐tomed to doing), you soon will be relegated to a hollow shell of therichness of JavaScript
While this subset has been famously dubbed “The Good Parts,” Iwould implore you, dear reader, to instead consider it the “The EasyParts,” “The Safe Parts,” or even “The Incomplete Parts.”
This You Don’t Know JS series offers a contrary challenge: learn and deeply understand all of JavaScript, even and especially “The Tough
Parts.”
Here, we address head-on the tendency of JS developers to learn justenough to get by, without ever forcing themselves to learn exactlyhow and why the language behaves the way it does Furthermore, weeschew the common advice to retreat when the road gets rough
Trang 11I am not content, nor should you be, at stopping once something
just works and not really knowing why I gently challenge you to
journey down that bumpy “road less traveled” and embrace all thatJavaScript is and can do With that knowledge, no technique, noframework, and no popular buzzword acronym of the week will bebeyond your understanding
These books each take on specific core parts of the language that aremost commonly misunderstood or under-understood, and divedeep and exhaustively into them You should come away from read‐ing with a firm confidence in your understanding, not just of thetheoretical, but the practical “what you need to know” bits
The JavaScript you know right now is probably parts handed down
to you by others who’ve been burned by incomplete understanding
That JavaScript is but a shadow of the true language You don’t really know JavaScript yet, but if you dig into this series, you will Read on,
my friends JavaScript awaits you
Review
JavaScript is awesome It’s easy to learn partially, and much harder to
learn completely (or even sufficiently) When developers encounter
confusion, they usually blame the language instead of their lack ofunderstanding These books aim to fix that, inspiring a strong
appreciation for the language you can now, and should, deeply know.
Many of the examples in this book assume
modern (and future-reaching) JavaScript engine
environments, such as ES6 Some code may not
work as described if run in older (pre-ES6)
engines
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and fileextensions
Preface | ix
Trang 12Constant width
Used for program listings, as well as within paragraphs to refer
to program elements such as variable or function names, data‐bases, data types, environment variables, statements, and key‐words
Constant width bold
Shows commands or other text that should be typed literally bythe user
Constant width italic
Shows text that should be replaced with user-supplied values or
by values determined by context
This element signifies a tip or suggestion
This element signifies a general note
This element indicates a warning or caution
Using Code Examples
Supplemental material (code examples, exercises, etc.) is availablefor download at http://bit.ly/ydkjs-up-going-code
This book is here to help you get your job done In general, if exam‐ple code is offered with this book, you may use it in your programsand documentation You do not need to contact us for permissionunless you’re reproducing a significant portion of the code Forexample, writing a program that uses several chunks of code fromthis book does not require permission Selling or distributing a CD-ROM of examples from O’Reilly books does require permission.Answering a question by citing this book and quoting example code
Trang 13does not require permission Incorporating a significant amount ofexample code from this book into your product’s documentationdoes require permission.
We appreciate, but do not require, attribution An attribution usu‐ally includes the title, author, publisher, and ISBN For example:
“You Don’t Know JavaScript: Up & Going by Kyle Simpson (O’Reilly).
Copyright 2015 Getify Solutions, Inc., 978-1-491-92446-4.”
If you feel your use of code examples falls outside fair use or the per‐mission given above, feel free to contact us at permis‐ sions@oreilly.com
Safari® Books Online
Safari Books Online is an on-demand digitallibrary that delivers expert content in bothbook and video form from the world’s lead‐ing authors in technology and business
Technology professionals, software developers, web designers, andbusiness and creative professionals use Safari Books Online as theirprimary resource for research, problem solving, learning, and certif‐ication training
Safari Books Online offers a range of plans and pricing for enter‐
Members have access to thousands of books, training videos, andprepublication manuscripts in one fully searchable database frompublishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press,Focal Press, Cisco Press, John Wiley & Sons, Syngress, MorganKaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress,Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Tech‐nology, and hundreds more For more information about SafariBooks Online, please visit us online
Preface | xi
Trang 14How to Contact Us
Please address comments and questions concerning this book to thepublisher:
O’Reilly Media, Inc
1005 Gravenstein Highway North
To comment or ask technical questions about this book, send email
to bookquestions@oreilly.com
For more information about our books, courses, conferences, andnews, see our website at http://www.oreilly.com
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Trang 15CHAPTER 1
Into Programming
Welcome to the You Don’t Know JS (YDKJS) series.
Up & Going is an introduction to several basic concepts of program‐
ming—of course we lean toward JavaScript (often abbreviated JS)specifically—and how to approach and understand the rest of thetitles in this series Especially if you’re just getting into programmingand/or JavaScript, this book will briefly explore what you need to get
up and going.
This book starts off explaining the basic principles of programming
at a very high level It’s mostly intended if you are starting YDKJS
with little to no prior programming experience, and are looking tothese books to help get you started along a path to understandingprogramming through the lens of JavaScript
you’ll want to learn more about and practice to get into program‐ ming There are also many other fantastic programming introduc‐
tion resources that can help you dig into these topics further, and Iencourage you to learn from them in addition to this chapter.Once you feel comfortable with general programming basics, Chap‐
programming Chapter 2 introduces what JavaScript is about, butagain, it’s not a comprehensive guide—that’s what the rest of the
YDKJS books are for!
1
Trang 16If you’re already fairly comfortable with JavaScript, first check out
jump right in!
Code
Let’s start from the beginning
A program, often referred to as source code or just code, is a set of
special instructions to tell the computer what tasks to perform Usu‐ally code is saved in a text file, although with JavaScript you can alsotype code directly into a developer console in a browser, which we’llcover shortly
The rules for valid format and combinations of instructions is called
a computer language, sometimes referred to as its syntax, much the
same as English tells you how to spell words and how to create validsentences using words and punctuation
Statements
In a computer language, a group of words, numbers, and operators
that performs a specific task is a statement In JavaScript, a statement
might look as follows:
a = b * 2
The characters a and b are called variables (see “Variables” on page
14), which are like simple boxes you can store any of your stuff in
In programs, variables hold values (like the number 42) to be used
by the program Think of them as symbolic placeholders for the val‐ues themselves
By contrast, the 2 is just a value itself, called a literal value, because it
stands alone without being stored in a variable
The = and * characters are operators (see “Operators” on page 8)—they perform actions with the values and variables such as assign‐ment and mathematic multiplication
Most statements in JavaScript conclude with a semicolon (;) at theend
The statement a = b * 2; tells the computer, roughly, to get thecurrent value stored in the variable b, multiply that value by 2, thenstore the result back into another variable we call a
Trang 17Programs are just collections of many such statements, whichtogether describe all the steps that it takes to perform your pro‐gram’s purpose.
Expressions
Statements are made up of one or more expressions An expression is
any reference to a variable or value, or a set of variable(s) andvalue(s) combined with operators
For example:
a = b * 2
This statement has four expressions in it:
• 2 is a literal value expression.
• b is a variable expression, which means to retrieve its current
value
• b * 2 is an arithmetic expression, which means to do the multi‐
plication
• a = b * 2 is an assignment expression, which means to assign
the result of the b * 2 expression to the variable a (more onassignments later)
A general expression that stands alone is also called an expression statement, such as the following:
A more common expression statement is a call expression statement
(see “Functions” on page 22), as the entire statement is the functioncall expression itself:
alert ( a );
Expressions | 3
Trang 18Executing a Program
How do those collections of programming statements tell the com‐
puter what to do? The program needs to be executed, also referred to
as running the program.
Statements like a = b * 2 are helpful for developers when readingand writing, but are not actually in a form the computer can directly
understand So a special utility on the computer (either an inter‐ preter or a compiler) is used to translate the code you write into com‐
mands a computer can understand
For some computer languages, this translation of commands is typi‐cally done from top to bottom, line by line, every time the program
is run, which is usually called interpreting the code.
For other languages, the translation is done ahead of time, called
compiling the code, so when the program runs later, what’s running
is actually the already compiled computer instructions ready to go
It’s typically asserted that JavaScript is interpreted, because your Java‐
Script source code is processed each time it’s run But that’s not
entirely accurate The JavaScript engine actually compiles the pro‐
gram on the fly and then immediately runs the compiled code
For more information on JavaScript compiling,
see the first two chapters of the Scope & Closures
title of this series
Try It Yourself
This chapter is going to introduce each programming concept withsimple snippets of code, all written in JavaScript (obviously!)
It cannot be emphasized enough: while you go through this chapter
—and you may need to spend the time to go over it several times—you should practice each of these concepts by typing the code your‐self The easiest way to do that is to open up the developer tools con‐sole in your nearest browser (Firefox, Chrome, IE, etc.)
Trang 19Typically, you can launch the developer console
with a keyboard shortcut or from a menu item
For more detailed information about launching
and using the console in your favorite browser,
see “Mastering The Developer Tools Console”
To type multiple lines into the console at once,
use <shift> + <enter> to move to the next
new line Once you hit <enter> by itself, the
console will run everything you’ve just typed
Let’s get familiar with the process of running code in the console.First, I suggest opening up an empty tab in your browser I prefer to
do this by typing about:blank into the address bar Then, make sureyour developer console is open, as we just mentioned
Now, type this code and see how it runs:
Trang 20tics of that statement that we should explain.
First, the log( b ) part is referred to as a function call (see “Func‐
to that function, which asks it to take the value of b and print it tothe console
Second, the console part is an object reference where the log( )
function is located We cover objects and their properties in moredetail in Chapter 2
Another way of creating output that you can see is to run an
alert( ) statement For example:
For this book, we’ll use console.log( ) for output
Input
While we’re discussing output, you may also wonder about input
(i.e., receiving information from the user)
The most common way that happens is for the HTML page to showform elements (like text boxes) to a user that she can type into, andthen use JS to read those values into your program’s variables.But there’s an easier way to get input for simple learning and dem‐onstration purposes such as what you’ll be doing throughout thisbook Use the prompt( ) function:
Trang 21age prompt ( "Please tell me your age:" );
console log ( age );
As you may have guessed, the message you pass to prompt( )—inthis case, "Please tell me your age:"—is printed into the popup
This should look similar to the following:
Once you submit the input text by clicking “OK,” you’ll observe thatthe value you typed is stored in the age variable, which we then out‐ put with console.log( ):
To keep things simple while we’re learning basic programming con‐cepts, the examples in this book will not require input But now thatyou’ve seen how to use prompt( ), if you want to challenge your‐self, you can try to use input in your explorations of the examples
Try It Yourself | 7
Trang 22This may seem like a strange reverse order to
specify assignment Instead of a = 42, some
might prefer to flip the order so the source value
is on the left and the target variable is on the
right, like 42 -> a (this is not valid JavaScript!)
Unfortunately, the a = 42 ordered form, and
similar variations, is quite prevalent in modern
programming languages If it feels unnatural,
just spend some time rehearsing that order in
your mind to get accustomed to it
Consider:
a = 2
b = a + 1
Here, we assign the 2 value to the a variable Then, we get the value
of the a variable (still 2), add 1 to it resulting in the value 3, thenstore that value in the b variable
While not technically an operator, you’ll need the keyword var in
every program, as it’s the primary way you declare (aka create) variables (see “Variables” on page 14)
You should always declare the variable by name before you use it
But you only need to declare a variable once for each scope (see
needed For example:
var 20 ;
a = a + 1
a = a * 2
Trang 23< (less than), > (greater than), <= (less than or loose-equals), >=
(greater than or loose-equals), as in a <= b
Logical
&& (and), || (or), as in a || b that selects either a or b
These operators are used to express compound conditionals(see “Conditionals” on page 18), like if either a or b is true
Operators | 9
Trang 24For much more detail, and coverage of operators
not mentioned here, see the Mozilla Developer
Network (MDN)’s “Expressions and Operators”
Values & Types
If you ask an employee at a phone store how much a certain phonecosts, and he says “ninety-nine, ninety-nine” (i.e., $99.99), he’s giv‐ing you an actual numeric dollar figure that represents what you’llneed to pay (plus taxes) to buy it If you want to buy two of thosephones, you can easily do the mental math to double that value toget $199.98 for your base cost
If that same employee picks up another similar phone but says it’s
“free” (perhaps with air quotes), he’s not giving you a number, butinstead another kind of representation of your expected cost ($0.00)
—the word “free.”
When you later ask if the phone includes a charger, the answer canonly be “yes” or “no.”
In very similar ways, when you express values in a programs, youchoose different representations for those values based on what youplan to do with them
These different representations for values are called types in pro‐
gramming terminology JavaScript has built-in types for each of
these so-called primitive values:
• When you need to do math, you want a number
• When you need to print a value on the screen, you need a
string (one or more characters, words, or sentences)
• When you need to make a decision in your program, you need a
boolean (true or false)
Values that are included directly in the source code are called liter‐ als string literals are surrounded by double quotes (" ") or sin‐gle quotes (' ')—the only difference is stylistic preference
number and boolean literals are just presented as is (e.g., 42, true,etc.)
Trang 25Beyond string/number/boolean value types, it’s common for pro‐
gramming languages to provide arrays, objects, functions, and more.
We’ll cover much more about values and types throughout thischapter and the next
Converting Between Types
If you have a number but need to print it on the screen, you need toconvert the value to a string, and in JavaScript this conversion iscalled “coercion.” Similarly, if someone enters a series of numericcharacters into a form on an ecommerce page, that’s a string, but ifyou need to then use that value to do math operations, you need to
coerce it to a number
JavaScript provides several different facilities for forcibly coercing
between types For example:
var "42" ;
var Number ( a );
console log ( a ); // "42"
console log ( b ); // 42
Using Number( ) (a built-in function) as shown is an explicit coer‐
cion from any other type to the number type That should be prettystraightforward
But a controversial topic is what happens when you try to comparetwo values that are not already of the same type, which would
require implicit coercion.
When comparing the string "99.99" to the number 99.99, mostpeople would agree they are equivalent But they’re not exactly thesame, are they? It’s the same value in two different representations,
two different types You could say they’re “loosely equal,” couldn’t
you?
Values & Types | 11
Trang 26To help you out in these common situations, JavaScript will some‐
times kick in and implicitly coerce values to the matching types.
So if you use the == loose-equals operator to make the comparison
"99.99" == 99.99, JavaScript will convert the left-hand side
"99.99" to its number equivalent 99.99 The comparison thenbecomes 99.99 == 99.99, which is of course true
While designed to help you, implicit coercion can create confusion
if you haven’t taken the time to learn the rules that govern its behav‐ior Most JS developers never have, so the common feeling is thatimplicit coercion is confusing and harms programs with unexpectedbugs, and should thus be avoided It’s even sometimes called a flaw
in the design of the language
However, implicit coercion is a mechanism that can be learned, and moreover should be learned by anyone wishing to take JavaScript
programming seriously Not only is it not confusing once you learnthe rules, it can actually make your programs better! The effort iswell worth it
For more information on coercion, see Chap‐
ter 2 of this title and Chapter 4 of the Types &
Grammar title of this series.
Code Comments
The phone store employee might jot down some notes on the fea‐tures of a newly released phone or on the new plans her companyoffers These notes are only for the employee—they’re not for cus‐tomers to read Nevertheless, these notes help the employee do herjob better by documenting the hows and whys of what she shouldtell customers
One of the most important lessons you can learn about writing code
is that it’s not just for the computer Code is every bit as much, if notmore, for the developer as it is for the compiler
Your computer only cares about machine code, a series of binary 0s
and 1s, that comes from compilation There’s a nearly infinite num‐
ber of programs you could write that yield the same series of 0s and1s The choices you make about how to write your program matter
Trang 27—not only to you, but to your other team members and even toyour future self.
You should strive not just to write programs that work correctly, butprograms that make sense when examined You can go a long way inthat effort by choosing good names for your variables (see “Vari‐
But another important part is code comments These are bits of text
in your program that are inserted purely to explain things to ahuman The interpreter/compiler will always ignore these com‐ments
There are lots of opinions on what makes well-commented code; wecan’t really define absolute universal rules But some observationsand guidelines are quite useful:
• Code without comments is suboptimal
• Too many comments (one per line, for example) is probably asign of poorly written code
• Comments should explain why, not what They can optionally explain how if what’s written is particularly confusing.
In JavaScript, there are two types of comments possible: a single-linecomment and a multiline comment
Consider:
var 42 ; // 42 is the meaning of life
Code Comments | 13
Trang 28The /* */ multiline comment is appropriate if you have severallines worth of explanation to make in your comment.
Here’s a common usage of multiline comments:
/* The following value is used because
it has been shown that it answers
every question in the universe */
The only thing that cannot appear inside a multiline comment is a
*/, because that would be interpreted to end the comment
You will definitely want to begin your learning of programming bystarting off with the habit of commenting code Throughout the rest
of this chapter, you’ll see I use comments to explain things, so do thesame in your own practice Trust me, everyone who reads your codewill thank you!
Variables
Most useful programs need to track a value as it changes over thecourse of the program, undergoing different operations as called for
by your program’s intended tasks
The easiest way to go about that in your program is to assign a value
to a symbolic container, called a variable—so called because the value in this container can vary over time as needed.
In some programming languages, you declare a variable (container)
to hold a specific type of value, such as number or string Static typ‐ ing, otherwise known as type enforcement, is typically cited as a ben‐
efit for program correctness by preventing unintended valueconversions
Other languages emphasize types for values instead of variables
Weak typing, otherwise known as dynamic typing, allows a variable
to hold any type of value at any time It’s typically cited as a benefitfor program flexibility by allowing a single variable to represent a
Trang 29value no matter what type form that value may take at any givenmoment in the program’s logic flow.
JavaScript uses the latter approach, dynamic typing, meaning vari‐ ables can hold values of any type without any type enforcement.
As mentioned earlier, we declare a variable using the var statement
—notice there’s no other type information in the declaration Con‐
sider this simple program:
var amount 99.99 ;
amount amount ;
console log ( amount ); // 199.98
// convert `amount` to a string, and
// add "$" on the beginning
amount "$" String ( amount );
console log ( amount ); // "$199.98"
The amount variable starts out holding the number 99.99, and thenholds the number result of amount * 2, which is 199.98
The first console.log( ) command has to implicitly coerce that
number value to a string to print it out
Then the statement amount = "$" + String(amount) explicitly
coerces the 199.98 value to a string and adds a "$" character to thebeginning At this point, amount now holds the string value
"$199.98", so the second console.log( ) statement doesn’t need
to do any coercion to print it out
JavaScript developers will note the flexibility of using the amount
variable for each of the 99.99, 199.98, and the "$199.98" values.Static-typing enthusiasts would prefer a separate variable like
amountStr to hold the final "$199.98" representation of the value,because it’s a different type
Either way, you’ll note that amount holds a running value thatchanges over the course of the program, illustrating the primary
purpose of variables: managing program state.
In other words, state is tracking the changes to values as your pro‐
gram runs
Variables | 15
Trang 30Another common usage of variables is for centralizing value setting.
This is more typically called constants, when you declare a variable with a value and intend for that value to not change throughout the
program
You declare these constants, often at the top of a program, so that it’sconvenient for you to have one place to go to alter a value if youneed to By convention, JavaScript variables as constants are usuallycapitalized, with underscores _ between multiple words
Here’s a silly example:
var TAX_RATE 0.08 ; // 8% sales tax
var amount 99.99 ;
amount amount ;
amount amount amount TAX_RATE );
console log ( amount ); // 215.9784
console log ( amount toFixed ( 2 ) ); // "215.98"
Similar to how console.log( ) is a function
log( ) accessed as an object property on the
console value, toFixed( ) here is a function
that can be accessed on number values JavaScript
numbers aren’t automatically formatted for dol‐
lars—the engine doesn’t know what your intent
is, and there’s no type for currency toFixed( )
lets us specify how many decimal places we’d
like the number rounded to, and it produces the
string as necessary
The TAX_RATE variable is only constant by convention—there’s noth‐
ing special in this program that prevents it from being changed But
if the city raises the sales tax rate to 9%, we can still easily update ourprogram by setting the TAX_RATE assigned value to 0.09 in oneplace, instead of finding many occurrences of the value 0.08 strewnthroughout the program and updating all of them
The newest version of JavaScript at the time of this writing (com‐monly called “ES6”) includes a new way to declare constants, byusing const instead of var:
Trang 31By the way, that kind of “protection” against mistakes is similar tothe static-typing type enforcement, so you can see why static types
in other languages can be attractive!
For more information about how different val‐
ues in variables can be used in your programs,
see the Types & Grammar title of this series.
Blocks
The phone store employee must go through a series of steps to com‐plete the checkout as you buy your new phone
Similarly, in code we often need to group a series of statements
together, which we often call a block In JavaScript, a block is defined
by wrapping one or more statements inside a curly-brace pair
ple:
Blocks | 17
Trang 32var amount 99.99 ;
// is amount big enough?
if amount 10 ) { // < block attached to `if`
Unlike most other statements like con
sole.log(amount);, a block statement does not
need a semicolon (;) to conclude it
Conditionals
“Do you want to add on the extra screen protectors to your pur‐chase, for $9.99?” The helpful phone store employee has asked you
to make a decision And you may need to first consult the current
state of your wallet or bank account to answer that question But
obviously, this is just a simple “yes or no” question
There are quite a few ways we can express conditionals (aka deci‐
sions) in our programs
The most common one is the if statement Essentially, you’re say‐
ing, “If this condition is true, do the following…” For example:
The if statement requires an expression in between the parentheses
( ) that can be treated as either true or false In this program, weprovided the expression amount < bank_balance, which indeed willeither evaluate to true or false, depending on the amount in the
bank_balance variable
Trang 33You can even provide an alternative if the condition isn’t true, called
an else clause Consider:
console log ( "I'll take the accessory!" );
amount amount ACCESSORY_PRICE ;
As we discussed in “Values & Types” on page 10, values that aren’talready of an expected type are often coerced to that type The if
statement expects a boolean, but if you pass it something that’s notalready boolean, coercion will occur
JavaScript defines a list of specific values that are considered “falsy”because when coerced to a boolean, they become false—theseinclude values like 0 and "" Any other value not on the “falsy” list isautomatically “truthy”—when coerced to a boolean they become
true Truthy values include things like 99.99 and "free" See “Tru‐
Conditionals exist in other forms besides the if For example, the
switch statement can be used as a shorthand for a series of
if else statements (see Chapter 2) Loops (see “Loops” on page
20) use a conditional to determine if the loop should keep going or
stop
Conditionals | 19
Trang 34For deeper information about the coercions that
can occur implicitly in the test expressions of
conditionals, see Chapter 4 of the Types & Gram‐
mar title of this series.
Loops
During busy times, there’s a waiting list for customers who need tospeak to the phone store employee While there’s still people on thatlist, she just needs to keep serving the next customer
Repeating a set of actions until a certain condition fails—in otherwords, repeating only while the condition holds—is the job of pro‐gramming loops; loops can take different forms, but they all satisfythis basic behavior
A loop includes the test condition as well as a block (typically as
{ }) Each time the loop block executes, that’s called an iteration.
For example, the while loop and the do while loop forms illustratethe concept of repeating a block of statements until a condition nolonger evaluates to true:
while numOfCustomers ) {
console log ( "How may I help you?" );
// help the customer
numOfCustomers numOfCustomers ;
}
// versus:
do
console log ( "How may I help you?" );
// help the customer
numOfCustomers numOfCustomers ;
} while numOfCustomers );
The only practical difference between these loops is whether theconditional is tested before the first iteration (while) or after thefirst iteration (do while)
Trang 35In either form, if the conditional tests as false, the next iterationwill not run That means if the condition is initially false, a while
loop will never run, but a do while loop will run just the first time.Sometimes you are looping for the intended purpose of counting acertain set of numbers, like from 0 to 9 (10 numbers) You can dothat by setting a loop iteration variable like i at value 0 and incre‐menting it by 1 each iteration
For a variety of historical reasons, programming
languages almost always count things in a
zero-based fashion, meaning starting with 0 instead
of 1 If you’re not familiar with that mode of
thinking, it can be quite confusing at first Take
some time to practice counting starting with 0 to
become more comfortable with it!
The conditional is tested on each iteration, much as if there is animplied if statement inside the loop
We can use JavaScript’s break statement to stop a loop Also, we canobserve that it’s awfully easy to create a loop that would otherwiserun forever without a breaking mechanism
This is not necessarily a practical form you’d
want to use for your loops It’s presented here for
illustration purposes only
Loops | 21
Trang 36While a while (or do while) can accomplish the task manually,there’s another syntactic form called a for loop for just that purpose:
The for loop has three clauses: the initialization clause (var i=0),the conditional test clause (i <= 9), and the update clause (i = i +
1) So if you’re going to do counting with your loop iterations, for is
a more compact and often easier form to understand and write.There are other specialized loop forms that are intended to iterateover specific values, such as the properties of an object (see Chap‐
erties have been processed The “loop until a condition fails”concept holds no matter what the form of the loop
Functions
The phone store employee probably doesn’t carry around a calcula‐tor to figure out the taxes and final purchase amount That’s a taskshe needs to define once and reuse over and over again Odds are,the company has a checkout register (computer, tablet, etc.) withthose “functions” built in
Similarly, your program will almost certainly want to break up thecode’s tasks into reusable pieces, instead of repeatedly repeatingyourself repetitiously (pun intended!) The way to do this is todefine a function
A function is generally a named section of code that can be “called”
by name, and the code inside it will be run each time Consider:
Trang 37amount amount ;
printAmount (); // "199.98"
Functions can optionally take arguments (aka parameters)—valuesyou pass in And they can also optionally return a value back:
function printAmount ( amt ) {
console log ( amt toFixed ( 2 ) );
console log ( amount ); // "$99.99"
The function printAmount( ) takes a parameter that we call amt.The function formatAmount() returns a value Of course, you canalso combine those two techniques in the same function
Functions are often used for code that you plan to call multipletimes, but they can also be useful just to organize related bits of codeinto named collections, even if you only plan to call them once.Consider:
const TAX_RATE 0.08 ;
function calculateFinalPurchaseAmount ( amt ) {
// calculate the new amount with the tax
amt amt amt TAX_RATE );
// return the new amount
return amt ;
}
var amount 99.99 ;
amount calculateFinalPurchaseAmount ( amount );
console log ( amount toFixed ( 2 ) ); // "107.99"
Although calculateFinalPurchaseAmount( ) is only called once,organizing its behavior into a separate named function makes thecode that uses its logic (the amount = calculateFinal state‐
Functions | 23
Trang 38ment) cleaner If the function had more statements in it, the benefitswould be even more pronounced.
Scope
If you ask the phone store employee for a phone model that herstore doesn’t carry, she will not be able to sell you the phone youwant She only has access to the phones in her store’s inventory.You’ll have to try another store to see if you can find the phoneyou’re looking for
Programming has a term for this concept: scope (technically called lexical scope) In JavaScript, each function gets its own scope Scope
is basically a collection of variables as well as the rules for how thosevariables are accessed by name Only code inside that function can
access that function’s scoped variables.
A variable name has to be unique within the same scope—therecan’t be two different a variables sitting right next to each other Butthe same variable name a could appear in different scopes:
Also, a scope can be nested inside another scope, just like if a clown
at a birthday party blows up one balloon inside another balloon Ifone scope is nested inside another, code inside the innermost scopecan access variables from either scope
Consider:
Trang 39So, code inside the inner() function has access to both variables a
and b, but code only in outer() has access only to a—it cannotaccess b because that variable is only inside inner()
Recall this code snippet from earlier:
const TAX_RATE 0.08 ;
function calculateFinalPurchaseAmount ( amt ) {
// calculate the new amount with the tax
amt amt amt TAX_RATE );
// return the new amount
return amt ;
}
The TAX_RATE constant (variable) is accessible from inside the calculateFinalPurchaseAmount( ) function, even though we didn’tpass it in, because of lexical scope
For more information about lexical scope, see
the first three chapters of the Scope & Closures
title of this series
Functions | 25
Trang 40There is absolutely no substitute for practice in learning program‐ming No amount of articulate writing on my part is alone going tomake you a programmer
With that in mind, let’s try practicing some of the concepts welearned here in this chapter I’ll give the “requirements,” and you try
it first Then consult the code listing below to see how I approachedit:
• Write a program to calculate the total price of your phone pur‐chase You will keep purchasing phones (hint: loop!) until yourun out of money in your bank account You’ll also buy accesso‐ries for each phone as long as your purchase amount is belowyour mental spending threshold
• After you’ve calculated your purchase amount, add in the tax,then print out the calculated purchase amount, properly for‐matted
• Finally, check the amount against your bank account balance tosee if you can afford it or not
• You should set up some constants for the “tax rate,” “phoneprice,” “accessory price,” and “spending threshold,” as well as avariable for your “bank account balance.”
• You should define functions for calculating the tax and for for‐matting the price with a “$” and rounding to two decimalplaces
• Bonus Challenge: Try to incorporate input into this program,
perhaps with the prompt( ) covered in “Input” on page 6 Youmay prompt the user for their bank account balance, for exam‐ple Have fun and be creative!
OK, go ahead Try it Don’t peek at my code listing until you’ve given
it a shot yourself!
Because this is a JavaScript book, I’m obviously
going to solve the practice exercise in JavaScript
But you can do it in another language for now if
you feel more comfortable