Infor & Preface
- Full name: You Don't Know JS Yet (2nd edition)
- Author: Kyle Simpson
- getify/You-Dont-Know-JS on Github
- It's not just for starters, but for all developers who want to understand deeper.
- "The primary point of the title โYou Donโt Know JS Yetโ is to point out that most JS developers donโt take the time to really understand how the code that they write works."
- "My suggestion is you take your time going through YDKJSY. Take one chapter, read it completely through start to finish, and then go back and re-read it section by section. Stop in between each section, and practice the code or ideas from that section. For larger concepts, it probably is a good idea to expect to spend several days digesting, re-reading, practicing, then digesting some more."
Chap 1 โ What is JS?
What's With That Name?
- 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".
Language Specification
- 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.
Many Faces
- 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 & Forwards
- 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.
// New if (something) { let x = 3; // "let" was added in ES6 (2015) console.log(x); } else { let x = 4; // "let" โ block scope console.log(x); }
// Old var x$0, x$1; // different variables if (something) { x$0 = 3; // diferent variables console.log(x$0); } else { x$1 = 4; console.log(x$1); }
ย
// NEW: .finally() โ ES2019 // getSomeRecords() returns us a promise for some // data it will fetch var pr = getSomeRecords(); // show the UI spinner while we get the data startSpinner(); pr.then(renderRecords) // render if successful .catch(showError) // show an error if not .finally(hideSpinner) // always hide the spinner
// OLD: // prevents running on engines already has this API if (!Promise.prototype.finally) { // define new for old engines Promise.prototype.finally = function f(fn){ return this.then( function t(v){ return Promise.resolve( fn() ) .then(function t(){ return v; }); }, function c(e){} ); }; }
What's in an Interpretation (Thi: โDiแป n dแปchโ)?
- 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.
Strictly Speaking
- 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
// only whitespace and comments are allowed // before the use-strict pragma "use strict"; // the rest of the file runs in strict mode
// Per function scope // Used when you wanna convert non-strict to strict programs function someOperations() { // whitespace and comments are fine here "use strict"; // all this code will run in strict mode }
- Cannot be default โ otherwise, it will break "backward compatibility" rule.
- Virtually, all transpiled codes (codes in production) ends up in strict mode.
Chap 2 โ Surveying JS
- 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.
Each File is a Program
- 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.
Value
- Values come in 2 forms in JS: primitive and object
- Primitive:
string,number,boolean,undefined,null,symbol - literals:
string,number,boolean stringliterals, eg:const name = "Thi"โ Using""or''is optional but should pick one and to use it consistently throughout the program.
// Also can use backtick `` console.log("My name is ${name}.") // Output: My name is ${name}. console.log(`My name is ${name}.`) // Output: My name is Thi.
This is called an interpolation
number, eg. 3.14 or Math.PIboolean: true, false.undefined as the single empty valueconsole.log(null === undefined) // false (not the same type) console.log(null == undefined) // true (but the "same value") console.log(null === null) // true (both type and value are the same) console.log(undefined === undefined) // true console.log(typeof null) // 'object' console.log(typeof undefined) // 'undefined'
symbol, eg. const a = Symbol("meaning of life") โ Symbols are mostly used in low-level code such as in libraries and frameworks.- Arrays:
names = ["France", 1, null] names.length // 3 names[0] // France typeof names // "object" โ yep! // array can contains a function const func = () โ true; arr = [func, 1] typeof func // "function"
Fact: JS array indices are 0-based (eg.
a[0])- Objects: an unordered, keyed collection of any various values
name = { first: "Thi", last: "Dinh", age: 30, specialties: [ "JS", "Drawing" ] }; console.log(`My name is ${ name.first }.`); // My name is Thi.
- Value Type Determination:
typeof 42; // "number" typeof "abc"; // "string" typeof true; // "boolean" typeof undefined; // "undefined" typeof null; // "object" โ yep! typeof { "a": 1 }; // "object" typeof [1,2,3]; // "object" โ yep! typeof function hello(){}; // "function"
Declaring and Using Variables
varvslet
var adult = true; if (adult) { var name = "Thi"; // โ "var" says "this variable will be seen by a wider scope" let age = 30; // โ "let" limit access to "block scope" } console.log(name) // Thi console.log(age) // Error!
Note:
var should be avoided in favor of let (or const) โ prevent confusing in scoping behaviors.letvsconstโ must giveconstan initial value and cannot re-assign.
const somethingToBeAssignedLater; // Error! const myBirthday = true; let age; age = 30; if (myBirthday) { age = age + 1; // OK! myBirthday = false; // Error! }
- However,
const odds = [1, 3, 5]; odds[1] = 7; // OK :( odds = []; // Error!
- ๐ก Use
constwhen you need a meaningful variable likemyBirthDayinstead of justtrue. Also, with primitive values,consthelps avoid confusion due to reassignment problems.
Functions
- In JS, the word "functions" takes a broader meaning of "procedure" โ a collection of statements can be invoked many times.
- Different types,
// Function declaration โ appear as a statement by itself function functionName(coolThings) { // ... return returnedValue; } // Association between "functionName" and "returnedValue" happens during // the compile phase, before the code is executed.
// Function as an expression // Could be "let", "var" const functionName = function(coolThings) { // ... return returnedValue; } // (Diff from func declaration) Function expression is not associated with // its identifier until that statement during runtime.
- 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
var whatToSay = { greeting() { console.log("Hello!"); }, question() { console.log("What's your name?"); }, answer() { console.log("My name is Thi."); } }; whatToSay.greeting(); // Hello!
- Check more in โAppendix A - So many function formsโ.
Comparisons
- 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)
3 === 3.0; // true "yes" === "yes"; // true null === null; // true false === false; // true 42 === "42"; // false "hello" === "Hello" // false true === 1; // fasle 0 === null; // fasle "" === null; // fasle null === undefined; // fasle
=== is lying (not really "strict"),NaN === NaN; // false Number.isNaN(NaN) === Number.isNaN(NaN) // true 0 === -0; // true Object.is(0, -0) // false โ should use it, like an "===="
=== 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โ)[ 1, 2, 3 ] === [ 1, 2, 3 ] // false { a: 42 } === { a: 42 } // false ( x โ x * 2) === ( x โ x * 2 ) // false
var x = [ 1, 2, 3 ]; var y = x; y === x; // true (Both point to the same "reference") y === [ 1, 2, 3] // false x === [ 1, 2, 3] // false
- Coercive Comparisons
- Coercion means a value of one type being converted to its respective representation in another type.
42 == "42"; // true ("42" is converted to number) 1 == true; // true
// Allowed but avoid to use "" == 0; // true 0 == false; // true
== and === do exactly the same thing, no difference whatsoever.===? โ Because >, <, >=, โ use coercive also!var arr = [ "1", "10", "100", "1000" ]; for (let i = 0; i < arr.length && arr[i] < 500; i++) { // will run 3 times }
// Watch out var x = "10" var y = "9" var z = 9 x < y // true (use alphabetical comparison of string instead) x < z // false
How We Organize in JS
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
newto instantiate it!
class Page { constructor(text) { this.text = text; } print() { console.log(this.text); } } class Notebook { constructor() { this.pages = []; } addPage(text) { var page = new Page(text); this.pages.push(page); } print() { for (let page of this.pages) { page.print(); } } } var mathNotes = new Notebook(); mathNotes.addPage("Arithmetic: + - * / ..."); mathNotes.addPage("Trigonometry: sin cos tan ..."); mathNotes.print(); // ..
mathNotes.addPage().- Class Inheritance
// Base class class Publication { constructor(title, author, pubDate) { this.title = title; this.author = author; this.pubDate = pubDate; } print() { console.log(`Title: ${this.title}, By: ${this.author}, On: ${this.pubDate}`); } }
// Extended classes class Book extends Publication { constructor(bookDetails) { super(bookDetails.title, bookDetails.author, bookDetails.pubishedOn); this.publisher = bookDetails.publisher; this.ISBN = bookDetails.ISBN; } print() { // overrides parent's print() super.print(); // call (again) parent's print() console.log(`Publisher: ${this.publisher}, ISBN: ${this.ISBN}.`); } } class BlogPost extends Publication { constructor(title,author,pubDate,URL) { super(title,author,pubDate); this.URL = URL; } print() { super.print(); console.log(this.URL); } }
super() delegates to parent's constructor for its initialization work.print() and child's print() can have the same name and co-exits โ called polymorphism!var YDKJS = new Book({ title: "You Don't Know JS", author: "Kyle Simpson", publishedOn: "June 2014", publisher: "O'Reilly", ISBN: "123456-789" }); YDKJS.print(); // Title: You Don't Know JS, By: Kyle Simpson, On: June 2014 // Publisher: O'Reilly, ISBN: 123456-789 var forAgainstLet = new BlogPost( "For and against let", "Kyle Simpson", "October 27, 2014", "<https://davidwalsh.name/for-and-against-let>" ); forAgainstLet.print(); // Title: For and against let, By: Kyle Simpson, On: October 27, 2014 // <https://davidwalsh.name/for-and-against-let>
- 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
function Publication(title,author,pubDate) { var publicAPI = { print() { console.log(`Title: ${this.title}, By: ${this.author}, On: ${this.pubDate}`); } }; return publicAPI; } function Book(bookDetails) { var pub = Publication( bookDetails.title, bookDetails.author, bookDetails.publishedOn ); var publicAPI = { print() { pub.print(); console.log(`Publisher: ${this.publisher}, ISBN: ${this.ISBN}.`); } }; return publicAPI; } function BlogPost(title,author,pubDate,URL) { var pub = Publication(title,author,pubDate); var publicAPI = { print() { pub.print(); console.log(URL); } }; return publicAPI; }
this. while modules, they're accessed as identifier variables in scope.// Their usage var YDKJS = Book({...}); YDKJS.print(); var forAgainstLet = BlogPost(); forAgainstLet.print();
new!- 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
importinstead. - Rewrite above publication module as,
// publication.js function printDetails(title,author,pubDate) { console.log(`...`); } export function create(title,author,pubDate) { var publicAPI = { print() { printDetails(title,author,pubDate); } }; return publicAPI; }
// blogpost.js import { create as createPub } from "publication.js"; function printDetails(pub,URL) { pub.print(); console.log(URL); } export function create(title,author,pubDate,URL) { var pub = createPub(title,author,pubDate); var publicAPI = { print() { printDetails(pub,URL); } }; return publicAPI; }
// main.js import { create as newBlogPost } from "blogpost.js"; var forAgainstLet = newBlogPost(...); forAgainstLet.print();
The Rabbit Hole Deepens
- 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.
Chap 3 โ Digging to the roots of JS
- Goal: shifts to some of the lower-level root characteristics of JS.
Iteration
- 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
valueanddoneproperties, where done is a boolean that isfalseuntil the iteration over the underlying data source is complete.
- Consuming Iterators
// given an iterator of some data source: var it = /* .. */;
for..of// loop over its results one at a time for (let val of it) { console.log(`Iterator value: ${ val }`); } // Iterator value: .. // Iterator value: .. // ..
โฆ operator)// An array spread var vals = [ ...it ]; // A functrion call spread doSomethingUseful( ...it );
- Iterables
- ES6 defined structure/collection types as iterables: strings, arrays, maps, sets and others.
// Array // an array is iterable var arr = [ 10, 20, 30 ]; // shallow copy an array using iterator consumption var arrCopy = [ ...arr ];
// String // iterate the characters in a string var greeting = "Hello world!"; var chars = [ ...greeting ]; // [ "H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!" ]
// Map // given two DOM elements, `btn1` and `btn2` var buttonNames = new Map(); buttonNames.set(btn1,"Button 1"); buttonNames.set(btn2,"Button 2"); // The [btn,btnName] syntax is called โarray destructuringโ. for (let [btn,btnName] of buttonNames) { btn.addEventListener("click",function onClick(){ console.log(`Clicked ${ btnName }`); }); }
for (let btnName of buttonNames.values()) { console.log(btnName); } // Button 1 // Button 2
for (let [idx,val] of arr.entries()) { console.log(`[${ idx }]: ${ val }`); } // [0]: 10 // [1]: 20 // [2]: 30
keys()), values-only (values()), entries (entries()).Closure
๐ย
- 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.
function greeting(msg) { return function who(name) { console.log(`${ msg }, ${ name }!`); }; } var hello = greeting("Hello"); var howdy = greeting("Howdy"); hello("Kyle"); // Hello, Kyle! hello("Thi"); // Hello, Thi! howdy("Grant"); // Howdy, Grant!
greeting() finishes running, are its variables msg removed from memory? โ No! Itโs because the closure. Since the inner function instances who are still alive (assigned to hello and howdy, respectively), their closures are still preserving the msg variables.function counter(step = 1) { var count = 0; return function increaseCount(){ count = count + step; return count; }; } var incBy3 = counter(3); incBy3(); // 3 incBy3(); // 6
count is preserved after each invocation of the inner function.- Closure is most common when working with asynchronous code, such as with callbacks.
function getSomeData(url) { ajax(url,function onResponse(resp){ console.log( `Response (from ${ url }): ${ resp }` ); }); } getSomeData("https://some.url/wherever"); // Response (from https://some.url/wherever): ...
onResponse(..) is closed over url. Even though getSomeData(..) finishes right away, the url parameter variable is kept alive.- No need the outer scope to be a function, just at least one variable in an outer scope accessed from an inner function
for (let [idx,btn] of buttons.entries()) { btn.addEventListener("click",function onClick(){ console.log(`Clicked on button (${ idx })!`); }); }
idx, preserving for it for as long as the click handler is set on the btn. Remember: this closure is not over the value (like 1 or 3), but over the variable idx itself.this keyword
- One of JSโs most powerful mechanisms and also most misunderstood.
- Misconceptions:
thisrefers to the function itself orthispoints 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.
function classroom(teacher) { return function study() { console.log( `${ teacher } says to study ${ this.topic }`); }; } var assignment = classroom("Kyle"); assignment(); // Kyle says to study undefined
this.topic prefers window in the browser but there is no global variable named โtopicโ โ undefined.var homework = { topic: "JS", assignment: assignment }; homework.assignment(); // Kyle says to study JS
this prefers homework.var otherHomework = { topic: "Math" }; assignment.call(otherHomework); // Kyle says to study Math
.call() method.- Benefit of
this-aware functions: more flexibly re-use a single function with data from different objects.
Prototypes
- 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
Afrom the its prototype linkageB.
- A series of objects linked together via prototypes is called the โprototype chainโ
var homework = { topic: "JS" }; homework.toString(); // [object object]
homework has only property topic but its default prototype linkage to Object.prototype which has toString(), valueOf(),โฆ- Object Linkage
- To define an object prototype linkage, use
Object.create()
var homework = { topic: "JS" }; var otherHomework = Object.create(homework); otherHomework.topic; // "JS"
var noLinkedObject = Object.create(null) creates an object that is not prototype linked anywhere!homework.topic; // "JS" otherHomework.topic; // "JS" otherHomework.topic = "Math"; otherHomework.topic; // "Math" homework.topic; // "JS" -- not "Math"
otherHomework, not in prototype.
- Read more in the section โAppendix A - Prototypal Classesโ.
thisrevisited
var homework = { study() { console.log(`Please study ${ this.topic }`); } }; var jsHomework = Object.create(homework); jsHomework.topic = "JS"; jsHomework.study(); // Please study JS var mathHomework = Object.create(homework); mathHomework.topic = "Math"; mathHomework.study(); // Please study Math
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 โWhy?โ
Asking the right questions is a critical skill of becoming a better developer.
Chap 4 โ The bigger picture
This final chapter divides JS languages into 3 main pillars.
Pillar 1: Scope and Closure
- 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 โ
Pillar 2: Prototypes
- 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โ.
Pillar 3: Types and Coercion
- 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.
With the Grain
- 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).
Appendix A โ Exploring further
Values vs References
- If you assign/pass a value itself, the value is copied. Primitives are held by values.
var myName = "Kyle"; var yourName = myName; myName = "Thi"; console.log(myName); // Thi console.log(yourName); // Kyle
- 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.
var myAddress = { street: "123 JS Blvd". city: "Austin", state: "TX" } var yourAddress = myAddress; myAddress.street = "456 TS Ave"; console.log(yourAddress.street); // 456 TS Ave
So many function forms
- Named function expression
// Could be "let" or "var" const awesomeFunc = function someName(arg) { // ... return amzingStuff; } awesomeFunc.name; // "someName" // "awesomeFunc" and "someName" are only linked at the runtime // ๐ They should have the same name!
- 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)
// generator function declaration function *two() { .. } // async function declaration async function three() { .. } // async generator function declaration async function *four() { .. } // named function export declaration (ES6 modules) export function five() { .. }
// IIFE (Immediately Invoked Function Expression) (function(){ .. })(); (function namedIIFE(){ .. })(); // asynchronous IIFE (async function(){ .. })(); (async function namedAIIFE(){ .. })();
- Arrow function expression
var f; f = () โ 42; f = x โ x * 2; f = (x) โ x * 2; f = (x,y) โ x * y; f = x โ ({ x: x * 2 }); f = x โ { return x * 2; }; f = async x โ { var y = await doSomethingAsync(x); return y * 2; }; someOperation( x โ x * 2 );
โ arrow function form."- As methods in classes
class SomethingKindaGreat { // class methods coolMethod() { .. } // no commas! boringMethod() { .. } } var EntirelyDifferent = { // object methods coolMethod() { .. }, // commas! boringMethod() { .. }, // (anonymous) function expression property oldSchool: function() { .. } };
Coercive Conditional Comparison
var x = 1; if (x) { // will run! } // you may think it's while (x == true) while (x) { // will run, once! x = false; }
// But? var x = "hello"; if (x) { // will run! } if (x == true) { // won't run :( }
Before the comparison, a coercion occurs, from whatever type
x currently is, to boolean.var x = "hello"; if (Boolean(x) == true) { // will run } // which is the same as: if (Boolean(x) === true) { // will run }
Prototypal โClassesโ
var Classroom = { welcome() { console.log("Welcome, students!"); } }; var mathClass = Object.create(Classroom); mathClass.welcome(); // Welcome, students!
mathClass object is linked via its prototype to a Classroom object. mathClass.welcome() is delegated to the method defined on Classroom.function Classroom() { // .. } Classroom.prototype.welcome = function hello() { console.log("Welcome, students!"); }; var mathClass = new Classroom(); mathClass.welcome(); // Welcome, students!
prototype (where the function is prototype linked to), but rather the prototype object to link to when other objects are created by calling the function with new.โ๏ธThis โprototypal classโ pattern is now strongly discouraged, use ES6โs
class instead:class Classroom { constructor() { // .. } welcome() { console.log("Welcome, students!"); } } var mathClass = new Classroom(); mathClass.welcome(); // Welcome, students!


