π List of all notes for this book. IMPORTANT UPDATE Nov 18, 2024: I've stopped taking detailed notes from the book and now only highlight and annotate directly in the PDF files/book. With so many books to read, I don't have time to type everything. In the future, if I make notes while reading a book, they'll contain only the most notable points (for me).
Infor & Preface
- Not related with Java at all, not just a script but a programming language.
- "Java" β attract mostlty Java programmers, "Script" β light weight.
- Official name specified by TC39 as "ECMAScript" (ES).
- JS in browsers or Node.js is an implementation of ES2019 standard.
- Hosted by ECMA.
- Don't use "JS6" or "ES8", use "ES20xx" or "JS".
- There is just one JS in the wild (not multiple versions).
- Environments run JS: browsers, servers, robots, lightbulbs,....
- Not all are JS, eg.
alert("Hello, JS!")
orconsole.log()
β they're just APIs of JS environments. - There are many "JS-looking" APIs:
fetch()
,getCurrentLocation()
,getUserMedia()
,... - They follow JS rules but just "guests", not official JS specifications.
- Complain "JS is so inconsistent!" β it's because the environment hehaviors work, not because of JS itself!
- Developer Tools (Inspect Element in Chrome, for example) are... tools for developers. They're NOT JS environment!
- Something works in Dev Tool, doesn't mean JS compiler will understand it.
- Paradigm-level code categories
- Procedural: organizes codes in a top-down, linear progression. β eg. C
- Object-oriented (OO/classes): organizes codes into classes. β eg. Java/C++
- Functional (FP): organizes codes into functions. β eg. Haskell
- JS is a multi-paradigm language. β "meaning the syntax and capabilities allow a developer to mix and match (and bend and reshape!) concepts from various major paradigms"
- Backwards compatibility:
- Code from the past should still work today β "we don't break the web" (TC39)
- Idea: JS developer can write code with confidence β their code won't stop working in new released versions.
- Once itβs in JS, it canβt be taken out because it might break programs, even if weβd really, really like to remove it!
- My idea to remember: old codes work with new engines but old engines may not work with new codes.
- Forward compatibility:
- Code from future don't break the web today.
- CSS & HTML is forward, not backward!
- Codes from the past may not work / work the same today.
- Feature from 2019 in a browser 2010 β page isn't broken! Unrecognized things will be skipped!
- My idea to remember: old engines work with new code but old codes may not work with new engine.
- JS is backwards compatibility + not forward compability
- Codes written today, will work in future JS engines.
- Codes written today may be broken in old JS engines.
- Why?
- "Markup" (HTML) / "Styling" (CSS) languages β easier to "skip over".
- "Programming language" (JS) β cannot skip something it doesn't understand (the rest may be effected!)
- Fill the gaps?
- JS has "forward-compability problems" (FC) (not compatible with old engines)
- How today codes can be used in an old engine? β use transpiling (using a tool to convert a source code of a program from one form to another)
- FC problems related syntax β use a transpiler (eg. Babel) β convert "new" JS syntax to "older" syntax.
- "Itβs strongly recommended that developers use the latest version of JS so that their code is clean and communicates its ideas most effectively." β Let the tools take care of converting.
- FC problems related to missing API method β use polyfill (aka "shim"). β Normally, a transpiler like Babel will detect and add it automatically.
Β
- To clearify JS is interpreted or compiled β see how errors are handled.
- Historically, scripted/interpreted languages were executed a top-down, line-by-line
- Parsing whole process before any execution
- "Parsed" language π€ "compiled" language: All compiled are parsed.
- JS code is parsed before it's executed. β "early errors" β JS is a parsed language
- JS is closer to compiled than interpreted (but not clearly a compiled or clearly a interpreted) β "meaning the tools (including the JS engine) process and verify a program (reporting any errors!) before it executes."
- Flow of a JS source program:
- Program leaves IDE β transpiled by Babel β packed by Webpack β ... β form1 β delivered to a JS engine.
- JS engine parses the code to an AST (Abstract Syntax Tree) β subsequent execution: form1 > AST > executable form.
- Engine convert that AST to a kind-of byte code β then to JIT (just in time) compiler.
- JS VM executes the program.
- Web Assembly (WASM) β augments what the web (including JS) can accomplish.
- 2013, "ASM.js" (a subset of JS lang, transpiled from C) was introduced (by Mozilla) to demonstrate the performance of JS engine where it can run an Unreal 3 game at full 60fps. β ASM.js is just a transpiled language (not for coding).
- After ASM.js > another group (also Mozilla's) released Web Assembly (WASM) β provide a path for non-JS program (like C) to be converted to a form that could run in the JS engine.
- WASM's format is entirely unlike JS β skipping the parsing/compilation JS engine normally does
- codes β WASM parsing/compilation β binary packed (easier for JS engine to understand) > JS engine execute them.
- Ex: Go program has threaded programming β WASM convert it β JS engine can understand (JS no need to have something like threads feature)
- π‘TC39 aren't stressed to add more features (from other "concurrent" languages) β just keep their rules, WASM will make the bridge.
- WASM isn't only for the web, also isn't JS.
- ES5 (2009) β "strict mode" β encourage better JS programs.
- Why?
- Not a restriction but rather a "guide" so that JS engine can optimize and effectciently run the code.
- Prevent some "stupid" coding ways when working in group, for example.
- In form of "early errors" β ex: disallows naming 2 function parameters the same.
- Some examples
- Cannot be default β otherwise, it will break "backward compatibility" rule.
- Virtually, all transpiled codes (codes in production) ends up in strict mode.
- The best way to learn JS is to start writing JS.
- Goal: get a better feel for it, so that we can move forward writing our own programs with more confidence.
- In JS, each standalone file is its own separate program. β for error handling.
- How multiple files talk together? β Only way: sharing their state + use "global scope".
- ES6 β module (also a file-based) β files are imported to module and be considered as a single module.
- JS does still treat each module separately
- A JS file: either standardlone or module.
- Values come in 2 forms in JS: primitive and object
- Primitive:
string
,number
,boolean
,undefined
,null
,symbol
- literals:
string
,number
,boolean
string
literals, eg:const name = "Thi"
β Using""
or''
is optional but should pick one and to use it consistently throughout the program.number
, eg.3.14
orMath.PI
boolean
:true
,false
.- The "emptiness": undefined, null (They're not the same!) β itβs safest and best to use only
undefined
as the single empty value symbol
, eg.const a = Symbol("meaning of life")
β Symbols are mostly used in low-level code such as in libraries and frameworks.
This is called an interpolation
- Arrays:
Fact: JS array indices are 0-based (eg.
a[0]
)- Objects: an unordered, keyed collection of any various values
- Value Type Determination:
var
vslet
Note:
var
should be avoided in favor of let
(or const
) β prevent confusing in scoping behaviors.let
vsconst
β must giveconst
an initial value and cannot re-assign.
- However,
- π‘ Use
const
when you need a meaningful variable likemyBirthDay
instead of justtrue
. Also, with primitive values,const
helps avoid confusion due to reassignment problems.
- In JS, the word "functions" takes a broader meaning of "procedure" β a collection of statements can be invoked many times.
- Different types,
- Function are values that can be assigned and passed as an argument. It's a special type of object.
- Functions can be assigned as properties of objects
- Check more in βAppendix A - So many function formsβ.
- Equal...ish
- We must be aware of the differences between an equality and equivalence comparisons.
- "Triple equal"
===
β Checking both the value and the type (in fact, all comparisons in JS, not just===
, does consider the type but===
disallow any kind of conversion while others do) ===
is lying (not really "strict"),===
isn't a structural equality but identity equality for object values β In JS, all object values are held by reference (Check more in section βAppendix A - Values vs Referencesβ)- "Deep comparison" for "structural equality" is more complicated than you think (even if you stringify them and then compare, it's not always correct). That's why JS doesn't give any mechanism for this.
- Coercive Comparisons
- Coercion means a value of one type being converted to its respective representation in another type.
- If the comparison is between the same value type, both
==
and===
do exactly the same thing, no difference whatsoever. - Why not just use
===
? β Because>
,<
,>=
,β
use coercive also! - Itβs still pretty likely youβre going to run into a case where the types may differ.
- Check more in section βAppendix A - Coercive Conditional Comparisonβ.
Two major patterns: Classes and Modules.
- Classes
- A class in a program is a definition of a "type" of custom data structure that includes both data and behaviors that operate on that data.
- Classes define how data structure works but not themselves concrete values. β to get a concrete value of a class, use
new
to instantiate it! - Behaviors (methods) can be only called by instance, not the classes, eg.
mathNotes.addPage()
.
- Class Inheritance
super()
delegates to parent's constructor for its initialization work.- Parent's
print()
and child'sprint()
can have the same name and co-exits β called polymorphism!
- Modules
- Like classes, modules can "include" or "access" the data and behaviors of other modules.
- From the early days of JS, modules was an important and common pattern, even without a dedicated syntax.
- Classical module
- In classes, data and methods are accessed with
this.
while modules, they're accessed as identifier variables in scope. - The only difference is with/without
new
! - ES Modules (ESM).
- 3 different things compared to the classicial modules,
- No need to define a wrapper function, ESMs are always file-based, one file one module.
- Whenever we wanna make an API public, use
export
, otherwise, we cannot call this API from another module. - We don't "instantitate" an ESM, use
import
instead. - Rewrite above publication module as,
- Recall, this chapter is just like a "brief" of JS world.
- "I'm serious when I suggest: re-read this chapter, maybe several times."
- Next chapters, we dig more.
- Goal: shifts to some of the lower-level root characteristics of JS.
- A βstandardizedβ approach to consuming data from a source one chunk at a time.
- ES6 standardized a specific protocol for the iterator pattern directly in the language.
next()
method whose return is an object called an iterator result.- The object has
value
anddone
properties, where done is a boolean that isfalse
until the iteration over the underlying data source is complete.
- Consuming Iterators
for..of
- Spread form (
β¦
operator)
- Iterables
- ES6 defined structure/collection types as iterables: strings, arrays, maps, sets and others.
- All built-in iterables in JS have 3 iterator forms: keys-only (
keys()
), values-only (values()
), entries (entries()
).
- Closure might be as important to understand as variables or loops.
- The presence or lack of closure is sometimes the cause of bugs (or even the cause of performance issues).
- Closure is part of the nature of a function. Objects donβt get closures, functions do.
- To observe a closure, you must execute a function in a different scope than where that function was originally defined.
- Closure is most common when working with asynchronous code, such as with callbacks.
- No need the outer scope to be a function, just at least one variable in an outer scope accessed from an inner function
- One of JSβs most powerful mechanisms and also most misunderstood.
- Misconceptions:
this
refers to the function itself orthis
points to the instance that a method belongs to. β Both are incorrect!
- (From previous section) When a function is defined, it is attached to its enclosing scope via closure.
- Function has another characteristic - execution context which is exposed to the function via
this
.
- Scope is static but execution context is dynamic, entirely dependent on how it is called.
- Benefit of
this
-aware functions: more flexibly re-use a single function with data from different objects.
- A prototype is a characteristic of an object.
- Think about a prototype as a linkage between two objects. Itβs hidden but there are ways to expose and observe it.
- Delegation: access props of
A
from the its prototype linkageB
.
- A series of objects linked together via prototypes is called the βprototype chainβ
- Object Linkage
- To define an object prototype linkage, use
Object.create()
var noLinkedObject = Object.create(null)
creates an object that is not prototype linked anywhere!
- Read more in the section βAppendix A - Prototypal Classesβ.
this
revisited
Unlike other languages, JSβs
this
is dynamic (itβs not resolved to homework
but jsHomework
and mathHomework
)Two objects linked to a common parent.
Asking the right questions is a critical skill of becoming a better developer.
This final chapter divides JS languages into 3 main pillars.
- Scopes are like buckets, and variables are like marbles you put into those buckets.
- Scopes nest inside each other. Variables at that level of scope (or higher/outer) are accessible. Lower/inner variables are hidden and inaccessible. β lexical scope.
- The scope is determined at the time the program is parsed (compiled).
- JS is lexically scoped because of 2 characteristics:
- Hoisting: variables declared anywhere are treated as theyβred declared at the beginning of the scope.
var
-declared variables are function scoped.
- Closure: When a function makes reference to variables from an outer scope, and that function is passed around as a value and executed in other scopes, it maintains access to its original scope variables β Reading:Β You Don't Know JS Yet 2 - Scope & Closures (Chap 1 β Chap 5)
- JS is one of very few language where you have the option to create objets directly and explicitly without first defining their structure in a class.
- Power of prototype system: the ability for 2 objects to connect with each other and cooperate dynamically through
this
. Classes are just one pattern on top of such power. We can see in another approach where we just use objects with prototype chain.
- Check to see βclasses arenβt the only way to use objectsβ.
- Developers should learn more about how JS manages type conversions and also type-aware tools like TypeScript or Flow (βstatic typingβ approaches).
- Donβt conclude that jSβs type mechanism is bad!
- Check . Donβt skip over this topic just because you heard that we should use
===
and forget about the rest.
- The grain of how most people approach and use JS. This series donβt presence opinion as fact or vice versa. Just follow the specification. Donβt argue with the opinion or misconception of you or of the others.
- The grain you really should pay attention is of how JS works, at the language level.
- The most important grain to recognize is how the existing program(s) youβre working on, and developers youβre working with, do stuff.
- Learn to write more readable code (for your teamates or yourself in the future).
- If you assign/pass a value itself, the value is copied. Primitives are held by values.
- References are the idea that two or more variables are pointing at the same value. Edit one, others change. In JS, only object values (arrays, objects, functions,...) are treated as references.
- Named function expression
- Should a function have a name? β "In my opinion [Kyle's], if a function exists in your program, it has a purpose; otherwise, take it out! And if it has a purpose, it has a natural name that describes that purpose."
- Some more forms (early 2020, maybe more)
- Arrow function expression
- "Since I donβt think anonymous functions are a good idea to use frequently in your programs, Iβm not a fan of using the
β
arrow function form."
- As methods in classes
Before the comparison, a coercion occurs, from whatever type
x
currently is, to boolean
.βοΈThis βprototypal classβ pattern is now strongly discouraged, use ES6βs
class
instead:Check the book to see excercies and solutions. There are 3 topics - comparisons, closure and prototypes.
Β