JAVASCRIPT
GRAMMAR
JAVASCRIPT GRAMMAR
JavaScript Grammar - Edition | - March 23, 2019JavaScript Grammar
I= March 23, 2019
Genre: Software Development
Publisher: Learning Curve Books
Imprint: Independently published
ISB 9781091212169
Author: Greg Sidelnikov (greg
[email protected])
Editors, volunteers, contributors: Grace Neufeld.
Primary purpose of Learning Curve Books publishing company is
to provide effective education for web designers, software engineers and all readers
who are interested in being edified in the area of web development.
This edition of JavaScript Grammar was created to speed up the learning process
of JavaScript — the language for programming websites, applications and robots!
For questions and comments about the book you may contact the author or send
an email directly to our office at the email address mentioned below
Special Offers & Discounts Available
Schools, libraries and educational organizations may qualify for special prices.
Get in touch with our distribution department at
[email protected]
. nm
Learning Curve Books
Learning Curve Books is a registered trademark of Learning Curve Books, LLC
License is required to distribute this volume in any form regardless of format or
price. All graphics and content is copyright of Learning Curve Books, LLC. unless
where otherwise stated
©2018 - 2019 Learning Curve Books, LLC.JavaScript Grammar
0.1 Foreword
1 Presentation Format
1.1 Creative Communication
11.1 Theory
1.1.2 Practical Examples
1.1.3 Source Code .
1.1.4 Color-Coded Diagrams
1.1.5 Dos and Dont’s
2 Chrome Console
2.0.1 Beyond Console Log
2.0.2 console.dir
2.0.3 console.error
2.0.4 console.time() and console.timeEnd()
2.0.5 console.clear .
3 > Welcome To JavaScript
3.1. Entry Point
3.1.1 Dos and Dont's
CAAA AGH
©
10
lL
iL
12
13
13
143.1.2
Dynamic Import
3.2 Strict Mode
3.3 Literal Values
3.4 Variables
3.5. Passing Values By Reference
3.6 Scope Quirks
4 Statements
4.0.1
4.0.2
5.0.5
5.0.6
5.0.7
5.0.8
5.0.9
5.0.10 Executing Methods On Primitive Types .
Evaluating Statements
Expressions
boolean
null
undefined
number
bigint
typeof
string
Template Strings
Symbol
6 Type Coercion Madness
6.0.1
Examples of Type Coercion
19
19
21
23
25
26
29
29
31
33
35
35
35
36
37
38
39
40
42
48
49
506.0.2
6.0.3
6.0.4
6.0.5
6.0.6
6.0.7
7 Scope
7.0.1
Adding Multiple Values
Operator Precedence
String To Number Comparison
Operator Precedence & Associativity Table
Lvalue and R-value
mull vs undef ined
Scope
7.1 Variable Definitions
Tl
7.1.2
713
714
715
71.6
8 Operators
8.0.1
8.0.2
8.0.3
8.0.4
8.05
8.0.6
8.0.7
8.0.8
Variable Types
Scope Visibility Differences
const .
const and Arrays
const and Object Literals
Dos and Dont's
Arithmetic
Assignment
String
Comparison
Logical
Bitwise
typeof
Ternary (?:)
55
55
56
58
60
61
63
64
64
2
72
78
78
78
79
81
81
83
83
84
84
85
86
878.0.9 delete
8.0.10 in
9 ...rest and ...spread
9.0.1 Rest Properties
9.0.2 Spread Properties
9.0.3. ...rest and ...spread
9.1. Destructuring Assignment
10 Closure
10.0.1 Arity
10.0.2. Currying
11 Loops
11.0.1 Types of loops in JavaScript
11.1 for loops
11.1.1 O-index based counter
11.1.2 The Infinite for Loop
11.1.3 Multiple Statements
11.2 for...of Loop
11.2.1 for...of and Generators
11.2.2 for...of and Strings .
11.2.3. for...of and Arrays
11.2.4 for...of and Objects
11.2.5 for...of loops and objects converted to iterables
11.3 for...in Loops
11.4 While Loops
87
87
89
89
91
91
96
101
109
109
lil
1
114
114
114
115
120
120
122
122
123
124
125
12511.4.1 While and continue
12 Arrays
12.0.1 Array.prototype.sort()
12.0.2 Array.forEach
12.0.3 Array.every
12.0.4 Array.some
12.0.5 Array-filter
12.0.6 Array.map
12.0.7 Array.reduce .
12.0.8 Practical Reducer Ideas
12.0.9 Dos and Dont's
12.0.10 Array flat()
12.0.11 Array.flatMap()
12.0.12 String. prototype.matchAlll()
12.0.13 Dos and Dont's
12.0.14 Comparing Two Objects .
12.0.15 Writing arremp
12.0.16 Improving objcmp
12.0.17 Testing objcmp on a more complex object
13 Functions
13.1 Functions
13.1.1 Function Anatomy .
126
129
129
131
132
133
133
134
134
135
136
138
138
139
143
144
146
147
148
151
151
15213.1.2 Anonymous Functions
13.1.3 Assigning Functions To Variables
13.2 Origin of this keyword
14 Higher-order Functions
14.0.1 Theory
14.0.2 Definition
14.03 Abstract
14.0.4 Iterators
14.0.5 Dos and Dont’s
15 Arrow Functions
15.0.1 Arrow Function Anatomy
16 Creating HTML Elements Dynamically
16.0.1 Setting CSS Style
16.0.2 Adding Elements To DOM with .appendChild method
16.0.3 Writing A Function To Create Elements . .
16.0.4 Creating objects using function constructors
17 Prototype
17.0.1 Prototype
17.0.2 Prototype on Object Literal
17.0.3. Prototype Link
17.0.4 Prototype Chain
17.0.5 Method look-up.
17.0.6 Array methods
153
153
158
159
159
161
161
162
166
167
170
179
180
181
182
186
187
188
189
190
191
192
19217.1 Parenting 194
17.1.1 Extending Your Own Objects bese e 194
17.1.2. constructor property 195
17.1.3 Function 196
17.2 Prototype In Practice... .. bees 197
17.2.1 Object Literal 197
17.2.2 Using Function Constructor 199
17.23 Prototype ........... bee 200
17.2.4 Creating objects using Object.create : 201
17.2.5 Back To The Future 202
17.2.6 Function Constructor. . amas 203
17.2.7 Along came new operator 205
17.28 The class keyword 206
18 Object Oriented Programming 207
18.1 Ingredient. er sass 207
18.2 FoodFactory .............. Bais 3 208
18.3 Vessel 208
18.4 Burner bee bee 209
18.5 Range Type and The Polymorphic Oven bee 210
18.6 Class Definitions 211
18.6.1 printjs.... 2.0.0... bee 211
18.6.2 Ingredient .. 2... bee eee e 212
18.6.3 FoodFactory 212
18.6.4 Fridge w a = “ « « 21318.6.5 convert.energy to-heat
18.6.6 Vessel
18.6.7 Burner
18.6.8 Range one
18.6.9 Putting It All Together
19 Event Loop
20 Call Stack
20.1 Execution Context
20.2 Execution Context In Code
20.2.1 Window / Global Scope
20.2.2 The Call Stack
20.2.3 .call(), .bind(), .apply()
20.2.4 Stack Overflow
214
215
2u7
218
221
225
229
231
232
233
233
236
2370.1 Foreword
We often think of the word " feature” as something that belongs to software prod-
ucts and services. Modern apps such as Instagram and Twitter have a " Follow”
feature, for example. Uploading a photo to your account is another feature!
But computer languages have features too. A function is a feature. A for loop
is a feature. So is the class keyword ~ all are computer language features.
In JavaScript some of these features are borrowed from other languages, while
many remain unique to its own design. Features such as this, class and const
may appear similar to their original C++ implementation, but in many cases they
are used in a completely unique way to JavaScript.
JavaScript is an evolving language. When EcmaScript 6 came out in June 2015 the
language experienced a Cambrian explosion of new features that radically changed
how JavaScript code should be written
New features like ...rest and ...spread syntax, arrow functions, template strings,
object destructuring are commonplace in modern JavaScript code. But just a
few years ago, even seasoned JavaScript developers with over a decade experience
with the language couldn't conceive of such concepts.
Functional Programming started to creep into JavaScript community seemingly at
the speed of light and higher-order functions (.map, .filter, reduce) tied to Array
methods, that remained dormant for many years, have gained increased popularity,
But JavaScript is a multi-paradigm language. Programmers who come from tra-
ditional Object Oriented Programming background will find themselves at home
after induction of the class keyword and a separate constructor function that
provides an alternative to the classic JavaScript object-function constructors.
The ES6 specification triggered a whole new breed of coders who have developed
more respect for a language that once was used to write primitive DOM scripts.
JavaScript engines that run in browsers (Chrome browser's V8, for example) have
matured and JavaScript is no longer looked at as a simple scripting language.
It's a whole new era of JavaScript development. Today, you may often stumble
upon a video titled Build a robot with JavaScript on YouTube. It is even
possible to build desktop applications for Windows 10 almost entirely in JavaScript.
2JavaScript frameworks and libraries like React and Vue abstract away some of
the classic JavaScript principles, making it quicker to build modular applications.
But this often comes at the expense of never having to understand vanilla JavaScript
at the beginner level — its common grammar.
JavaScript Grammar was written to solve this problem by using carefully chosen
subjects that, hopefully, match a natural learning experience. Content of this book
will try to remain faithful to dynamic nature of JavaScript specification
Finally, it is hoped that this book will encourage the reader to take the next step
in the direction of more advanced subjects in the future.Chapter 1
Presentation Format
This book was structured with continuity in mind: it is meant to be read from
first to last page in a consecutive order. However, it can also be used as a desk
reference for looking up isolated examples when you need them.
JavaScript Grammar is not a complete JavaScript reference or manual. But,
this is probably a good thing, The subjects were reduced to only what's important
in modern-day JavaScript environment.
Namely: imports, classes, constructors, key principles behind functional program-
ming, including many features ranging from ES5 - ES10 are covered in this book.
The distinction between "ES" specifications has become less relevant. Al of it is
JavaScript. But just to give the reader a bit of perspective...
Sometimes you will see labels like this one.
This simply means that this feature was added to JavaScript as part of the Ec-
maScript’s ES10 specification.
1.1. Creative Communication
Some of JavaScript is easy, some of it is difficult. Not everything can be explained
by source code alone. Some things are based on intangible ideas or principles.
5Throughout this tutorial book you will come across many creative communication
devices, designed to make the learning process a bit easier and perhaps more fun.
One example of that is color-coded diagrams.
1.1.1 Theory
Not all subjects require extensive theory. On the other hand, some things won't
make any sense without it. Additional discussion will be included, where it becomes
absolutely necessary, in order to fully understand a particular concept
1.1.2 Practical Examples
A practical example follows the theoretical discussion, so we can actually see the
plementation. It will usually be explained by a source code listing,
1.1.3. Source Code
Source code listings will be provided to cement the foundational principles from
preceding text.
054| // Create (instantiate) a sparrow from class Bird
055 let sparrow = new Bird("sparrow", "gray");
056 sparrow. fly()3
057 Sparrow.walk() ;
058 sparrow. lay_egg();
059 Sparrow.talk(); // Error, only Parrot can talk
This is an example of instantiating sparrow object from Bird class and using
some of its methods.
1.1.4 Color-Coded Diagrams
A significant amount of effort went into creating diagrams describing fundamental
ideas behind JavaScript. They were designed for communicative value, hopefully
6they will speed up the learning process in places where hard to grasp abstract ideas
need to be explained visually.
‘There are two types of diagrams in this book: abstract ideas and source code
close ins
Abstract ideas
Sometimes there isn’t a way to explain an abstract idea or its structure without a
diagram. In places where that's the case, a diagram will be shown
f Function
Class.constructor
Figure 1.1: Class constructor is an object-function of type Function.
Here is another diagram visualizing anatomy of a JavaScript function:
arguments
name C, 0 default parameter
function update (a,b,¢,d = parameters
{—a37
bf
ost
3 hi"
arguments; array-like object of arguments [7,[],{},"hi"]
this; context: window or abject instance
return true; return value
Figure 1.2: JavaScript function anatomy.
7Code close
Most of the source code is accompanied by source code listings.
But when we need to close in on a particular important subject, a slightly larger
diagram with source code and additional color-coded highlighting will be shown
For example, here is exploration of an anonymous function when used in the context
of a event callback function
setTimeout(function() {
console.log("Print something in 1 second.
console. log (arguments) ;
3, 1000);
Figure 1.3: Anonymous function used as a set Timeout event callback
In this case the source code will be missing line numbers because it's not important.
Content
We won't spend much book space or your time on countless listings of functions
and available methods on every single object. This type of information can be
easily looked up and practiced online on demand from Mozilla's MDN web docs,
W3Schools and StackOverflow.
Much of content of this book is tailored to modern JavaScript development, which
leans toward >= EcmaScript6 specification, functional programming: the use of
higher-order Array functions, arrow functions and understanding execution context.
1.1.5 Dos and Dont’s
An occasional Dos and Donts section will appear with insightful tips.Chapter 2
Chrome Console
2.0.1 Beyond Console Log
Many programmers only know Chrome’s console. log but the console API con-
tains few other methods that have practical use, especially when time is of essence.
copy(obj) function
Copying JSON representation of an existing object to your copy buffer:
> let x = { property: 1, propi: 2, method: function(){} }5
> copy(x)s
>|
Now the JSON is in your copy-paste buffer, you can paste it into any text editor.
In this example x is a simple self-created object. But imagine a situation where a
much more complex object is returned from a database API
Note: Only JSON is returned, this means that methods will not make it to the
copy buffer. (JSON string format does not support methods, only properties.)
92.0.2 _console.dir
If you want to take a look at all object's properties and methods, you can print it
out directly into the console using console.dir method
> console. din(x);
vobject
> method: £ ()
propi: 2
property: 1
> __proto_: Object
>|
What's fantastic is that you can even output DOM elements:
> console. dir (document. body) ;
accesskey:
assignedSlot: null
» attributestyleMap: StylePropertyMap {size: 0}
> attributes: NamedNodeMap {length: o}
autocapitalize: ""
background: ""
baseURI: “http: //localhost/experiments/ javascript .html"
bgcolor: ""
102.0.3 console.error
001 let fuel = 995
002 function launch_rocket() {
003 function warning_msg() {
004 console.error("Not enough fuel."
005}
006 if (fuel >= 100) {
007 // looks Like everything's ok
00g =} else
009 warning_msg()5
o10 }
011
012 launch_rocket();
The great thing about console. error is that it also provides the stack trace:
© vNot enough fuel.
warning_msg @ javascript-x.html:9
launch_rocket @ javascript-x.html:14
(anonymous) @ javascript-x. htm]:17
>|
2.0.4 console.time() and console.timeEnd()
You can track the amount of time between function calls. This can be helpful
when optimizing code
002 let arr = new Array(16000) ;
003 for (let 1 = 0; 1 < arr.length; i++) {
004) arr{i] = new Object()5
005| }
Console output:: 2.51708984375ms
2.0.5 console.clear
Console was cleared
undefined
>|
Printing Objects
In JavaScript all objects have .toString() method. When providing an object
to console. log(value) it can print it either as an object, or as a string
001 let obj = {35
002 console. log (obj) ; J obj
003 console. log("object = " + obj); // [object Object]
004 console. log(* ${obj}"); // [object Object]
12Chapter 3
Welcome To JavaScript
3.1 Entry Point
Every computer program has an entry point.
You can start writing your code directly into
010°
011,
012)