A book series on JavaScript. @YDKJS on twitter.

Overview

You Don't Know JS Yet (book series) - 2nd Edition

This is a series of books diving deep into the core mechanisms of the JavaScript language. This is the second edition of the book series:

     ...

To read more about the motivations and perspective behind this book series, check out the Preface.

If you're looking for the previous first edition books, they can be found here.

Premier Sponsor

This edition of the YDKJS book series is exclusively sponsored by Frontend Masters.

Frontend Masters is the gold standard for top-of-the-line expert training material in frontend-oriented software development. With over 150 courses on all things frontend, this should be your first and only stop for quality video training on HTML, CSS, JS, and related technologies.


I teach all my workshops exclusively through Frontend Masters. If you like this book content, please check out my video training courses.

I want to extend a warm and deep thanks to Marc Grabanski and the entire Frontend Masters team, not only for their excellent work with the video training platform, but for their unwavering support of me and of the "You Don't Know JS" books!


Titles

I recommend reading the second edition books in this order:

If you're looking for the previous first edition books, they can be found here.

Publishing

As always, you'll be able to read these books online here entirely for free.

This edition of the books is being self-published through GetiPub publishing. The published books will be made available for sale through normal book retail sources.

If you'd like to contribute financially towards the effort (or any of my other OSS efforts) aside from purchasing the published books, please consider these options:

Contributions

Please feel free to contribute to the quality of this content by submitting PRs for improvements to code snippets, explanations, etc. While typo fixes are welcomed, they will likely be caught through normal editing/publishing processes, so please don't worry about them right now.

Any contributions you make to this effort are of course greatly appreciated.

But PLEASE read the Contributions Guidelines carefully before submitting a PR.

License & Copyright

The materials herein are all © 2019-2020 Kyle Simpson.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Unported License.

Comments
  • "types & grammar": review - vball525

    For reference I am testing using JSFiddle with Chrome 36, Firefox 30, and IE 11.

    Chapter 1 - Looks real good and all examples worked. Chapter 2

    • Strings Section
      • In the first example "b !== d;" is returning True instead of False as stated. All 3 browsers. try { var a = "foo"; var b = ["f","o","o"]; document.write(a.length); document.write(' '); // 3 document.write(b.length); document.write(' '); // 3 document.write(a.indexOf( "o" )); document.write(' '); // 1 document.write(b.indexOf( "o" )); document.write(' '); // 1 var c = a.concat( "bar" ); // "foobar" var d = b.concat( ["b","a","r"] ); // ["f","o","o","b","a","r"] document.write(c); document.write(' '); document.write(d); document.write(' '); document.write(a === c); document.write(' '); // false document.write(b !== d); document.write(' '); // false document.write(a); document.write(' '); // "foo" document.write(b); document.write(' '); // ["f","o","o"] } catch(ex) { alert(ex); }
    opened by ghost 75
  • "es6 & beyond": ch 7, errors in example code

    Symbol.hasInstance requires Object.defineProperty (b/c non-configurable property on Function.prototype):

    Foo[Symbol.hasInstance] = function(inst) {
        return inst.greeting == "hello";
    };
    

    Needs to be:

    Object.defineProperty(Foo, Symbol.hasInstance, {
      value: function (inst) {
        return inst.greeting == "hello";
      },
      configurable: true
    });
    

    The additive operator calls ToPrimitive without a hint, that means the hint argument for Symbol.toPrimitive is "default":

    arr[Symbol.toPrimitive] = function(hint) {
        if (hint == "number") {
            // sum all numbers
            return this.reduce( function(acc,curr){
                return acc + curr;
            }, 0 );
        }
    };
    

    Needs to be:

    arr[Symbol.toPrimitive] = function(hint) {
        if (hint == "number" || hint == "default") {
            // sum all numbers
            return this.reduce( function(acc,curr){
                return acc + curr;
            }, 0 );
        }
    };
    

    true and false need to be switched for the Symbol.unscopables example.

    o[Symbol.unscopables] = {
        a: true,
        b: false,
        c: true
    };
    

    =>

    o[Symbol.unscopables] = {
        a: false,
        b: true,
        c: false
    };
    
    Some of the functions will look familiar as functions of the same names on Object:
        ...
        Reflect.ownKeys(..) --> Object.getOwnPropertyNames(..)
    

    Not quite correct, Reflect.ownKeys(..) returns the union of Object.getOwnPropertyNames(..) and Object.getOwnPropertySymbols(..).

    Also, Reflect.has(..) corresponds to the Object.prototype.hasOwnProperty(..) method. Essentially, Reflect.has(o,"foo") performs o.hasOwnProperty("foo").
    

    Wrong, Reflect.has(object, key) performs key in object.

    You can enumerate an object's values, essentially identical to consuming its @@iterator with ... or for..of, with Reflect.enumerate(..). For example, Reflect.enumerate([1,2,3]) would consume the iterator of the array, and return the received values as another [1,2,3] array.
    

    Wrong, Reflect.enumerate(..) returns the enumerable properties (including prototype properties) like for..in, e.g. [...Reflect.enumerate([1,2,3])] returns [ "0", "1", "2" ].

    And in "Tail Call Optimization (TCO)" it should be noted that tail calls are only valid in strict mode code. Maybe also add "use strict"; to the examples?

    editorial 
    opened by anba 40
  • `let` hoisting?

    `let` hoisting?

    Hi, thanks for taking the time to write such a great book! I'm working my way through it - in Chapter 3, you talk about hoisting let variables. Specifically:

    However, declarations made with let will not hoist to the entire scope of the block they appear in. Such declarations will not observably "exist" in the block until the declaration statement.

    {
       console.log( bar ); // ReferenceError!
       let bar = 2;
    }
    

    Even though the variable bar isn't initialized as undefined, it seems that they are still created.

    Using the example from this article as an example,

    let x = 'outer scope';
    (function() {
        console.log(x); // Reference error
        let x = 'inner scope';
    }());
    

    Do you think it would be helpful to add a clarification regarding the meaning of "hoisting" (since x here is technically still being created at the top of the block - it's just not initialized and can't be accessed), or perhaps just include a similar example?

    EDIT: removed extra console.log in the example that may have caused confusion

    question 
    opened by dxu 39
  • Tech Editors

    Tech Editors

    I'm seeking out folks who want to be official tech reviewers for this book series (to work with the editors at O'Reilly). You will review the drafts as posted here and provide technical feedback, also here, which can be addressed as revisions during the editing/production phase.

    You should have a solid understanding of the core parts of JavaScript (not just frameworks). :)

    If you're interested, please leave your contact info in a comment below, and @bmacdonald-oreilly will get in touch with you!

    question help wanted editorial 
    opened by getify 28
  • "this & object prototypes": cover shadowing properties

    Cover:

    1. Setting a shadowed property:

      var o = { a: 2 };
      var f = Object.create( o );
      f.a; // 2 -- accessed via delegation from `f` to `o`
      f.a = 5;
      f.a; // 5 -- created a shadowed property on `f`!
      o.a; // 2 -- still intact
      
    2. Strangely, shadowing cannot be done in the case of a property having been marked as writable:false:

      var o = { };
      Object.defineProperty( o, "a", { value:2, writable:false } );
      var f = Object.create( o );
      f.a; // 2 -- accessed via delegation from `f` to `o`
      f.a = 5;
      f.a; // 2 -- wtf!? didn't let us create a shadowed property on `f`?
      o.a; // 2 -- still intact
      
    3. Also strangely, a getter/setter prevents shadowing too:

      var o = { };
      Object.defineProperty( o, "a", { set: function(){}, get: function(){ return 2; } } );
      var f = Object.create( o );
      f.a; // 2 -- accessed via delegation from `f` to `o`
      f.a = 5;
      f.a; // 2 -- wtf!? didn't let us create a shadowed property on `f`?
      o.a; // 2 -- still intact
      

    To be clear, in cases 2) and 3) above, the [[Set]] algorithm consults the descriptor of the o.a property and actually uses the o.a to attempt the = 5 assignment, which fails for 2) and has no effect for 3). In neither of those cases does shadowed f.a get created.

    But in case 1) above, the descriptor for o.a isn't special, so o.a isn't used at all, and f.a = 5 creates shadowed f.a.

    This WTF inconsistency between 1) and 2)/3) here is what's at issue to me.

    opened by getify 23
  • "up & going": Ch1 Practice. Purchase is always unaffordable

    Can you improve on the Ch 1 practice? Because despite any changes to the constants in the Ch 1 Practice solution, the purchase is always unaffordable. That is it always comes back with "You can't afford this purchase. :(" I tested this by copy/pasting the very text from the digital book into my console. I did it again and again using different values in the constants for the threshold, prices, bank balance, etc... Always You can't afford this purchase. :("

    for second edition 
    opened by mvg73 17
  • Does `const` declaration is subject to the Variable Hoisting?

    Does `const` declaration is subject to the Variable Hoisting?

    From ES6 & Beyond - Chapter 2: Syntax I couldn't understand whether const declaration is subject to the variable hoisting?

    example:

    ;(function () {
        "use strict";
    
         const x = 3;
    
         function foo() {
             console.log("const x: ", x);
             console.log("const y: ", y);
         };
    
         const y = 5;
    
         foo();
    
    })();
    

    In the example above function foo is declared before const y declaration so according to Scope & Closures - Chapter 2: Lexical Scope which states that: "No matter where a function is invoked from, or even how it is invoked, its lexical scope is only defined by where the function was declared." foo should throw an error when it's called, but in this example when foo is called it does log x and y values. So how does it possible if const does not hoisted.

    opened by Konrud 16
  • Up & going equality 3 simple rules

    Up & going equality 3 simple rules

    Hi, I just finish the Up and Going book and now Javascript makes much more sense to me. Thank you.

    However when talking about Equality you give the example of "42" == 42 is true and "42" === 42 is false. So far no issues with it.Understood why how you got there. Few lines below (page 38) you mention the your few simple rules:

    • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===. • If either value in a comparison could be of these specific values (0, "", or []—empty array), avoid == and use ===. • In all other cases, you’re safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves read‐ ability.

    How is "42" == 42 would be safe? The third rule should have better explanation?

    Thank you

    for second edition 
    opened by flaviafm 16
  • Up & Going - Chapter 2 - Values & Types: Should

    Up & Going - Chapter 2 - Values & Types: Should "function" be included in the summary list of types?

    Given

    var a = function () { };
    typeof a;   // "function"
    

    Should that be included in this section just for completeness' sake?

    I know it's mentioned further down, but it might be good to put in that summary list given the importance of functions in JS.

    for second edition 
    opened by jlem 15
  • "async & performance" - ljharb

    Preface:

    • I still prefer "ham : hamburger" rather than "car : carnival" :-p

    Chapter 1:

    • Async Console: "serializing it to a string" - technically serializing it to any primitive will work. not sure if it's worth mentioning
    • I find your code spacing to be really weird - ie data.map( function(val){ instead of the more common data.map(function (val) {, and the spaces inside the parens for the ajax calls. Is that intentional? Even if it's your preferred style, and if it's consistent, you still may want to consider using more common whitespacing forms to avoid reader confusion.
    • I see that you're intentionally using splice, but that's one of the most confusing Array methods, and mutates the array. Is there another way of writing that code that doesn't use splice, or mutation? I think it would read much more clearly.
    • Is it worth noting that the HTML5 spec means that setTimeout can't possibly schedule any sooner than 4ms, and prior to HTML5 it was like 20ms?

    Chapter 2:

    • "node style" - this is worth a note explaining that it's because that's the convention used in node.js, otherwise there's no context
    • this was excellently written, btw. it re-convinced me of what i already knew, thoroughly.

    Chapter 3:

    • the "immediately" note is good, but perhaps another word or phrase instead would be better? "immediately" is pretty tightly coupled conceptually to "synchronously" in my head.
    • i like the receipt, and it's a better example than "go to a mall restaurant, you get a pager, when it buzzes your table is ready" but it fits better in my head. no changes necessary, just thinking out loud.
    • s/methaphorically/metaphorically
    • any note about .catch in ES6?
    • your ducktyping thenable code could be much simplified - if (p && typeof p.then === 'function') - which also would cover a primitive if i'd set up Number.prototype.then, for example (not that that would be a good idea)
    • the emphasis on "completion"/"continuation" seems strange; i've never really heard them used before - and the term "event" is pretty overloaded. This could stand to be reworded to avoid conflation with other topics, or to avoid placing emphasis on terms that aren't actually commonplace. The .on notation is jquery/backbone/etc standard, but isn't part of the language or the DOM, so it might not be helpful.
    • "// A B <-- not B A as you might expect" - i see "p3" is sync resolved (1 on microtask queue), "p1" is sync resolved and synchronously assumes (or should, as i understand it) the internal state of "p3" (so, 2 on microtask queue), "p2" is sync resolved (3 on microtask queue). p1's "then" will execute at microtask 2, p2's "then" at microtask 3. Thus, the microtasks will execute as 1,2,3, which means p1's "then" (B) and then after, p1's "then" (A). I agree (running the code) that it outputs A B, but obviously I'm missing something. This is not well explained, and I still don't understand what's going on. I assume it's some nuance of the spec, but fully talking out the algorithm may be helpful.
    • more explanation of Promise.race (like you did with Promise.all) would be helpful here
    • the place where you talk about an error in the first arg of "then" not firing the second arg of "then" is why Promise#catch is so useful - it would be great for it to have been introduced above.
    • finally got to "catch" :-) but i still think sooner is better.
    • glad to see you came around on "resolve" vs "fulfill" ;-)
    • you may want to link to "The point of promises is to give us back functional composition and error bubbling in the async world." https://gist.github.com/3889970 somewhere, it's awesome
    • holy crap, Promise.race() rejects but Promise.race([]) stays pending forever. i'm not on board with the error throwing stuff you believe, but this one i agree is utterly insane.
    • I'm really not a fan of the casual way your code examples modify globals. Is that really necessary to illustrate the point? (Promise.map, for example). That stuff is widely considered a horrible practice, and with no immediate notes every time you do it advising that it may be a bad idea, people will copy it, to their detriment.
    • no link to the es6-shim? :-)
    • "splitting values": foo doesn't return two values, it returns one, an array. that there's two things inside it is irrelevant. i think you're blurring the line here a bit too much.
    • worth talking about the ES6 ... spread operator vs a spread method, and vs destructuring?
    • Observables are proposed for ES7, might be worth mentioning https://github.com/jhusain/asyncgenerator
    • sigh, Promise.wrap. another global mutation. That one explicitly assumes a node-style callback. That's not going to work on everything.

    Chapter 4:

    • coming soon
    editorial 
    opened by ljharb 15
  • Spanish translation

    Spanish translation

    Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line). How about translating these books to another language? I can contribute. Been doing this for another cool book

    opened by EstebanMarin 13
  • Backward and forward compatibility in Javascript specification

    Backward and forward compatibility in Javascript specification

    Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line).


    Please type "I already searched for this issue": "I already searched for this issue"

    Edition: 2nd

    Book Title: Get Started

    Chapter: 1

    Section Title: Backwards & Forwards

    Question:

    Question I have is whether Babel transpiler is used to produce forward or backward compatible version of Javascript code.

    From official documentation from Babel:

    Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

    But in the book, you mentioned:

    Developers should focus on writing the clean, new syntax forms, and let the tools take care of producing a forwards-compatible version of that code that is suitable to deploy and run on the oldest-supported JS engine environments.

    I was conflicted whether to say Babel produces forward or backward compatible version of Javascript code, given how Babel doc and many people on internet refer to Babel as backward compatible.

    I'm just curious about your opinion on this.

    opened by Zerro97 1
  • duplicate `.editorconfig` config, typo, sample code and grammar

    duplicate `.editorconfig` config, typo, sample code and grammar

    Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line).

    Specifically quoting these guidelines regarding typos:

    Typos?

    Please don't worry about minor text typos. These will almost certainly be caught during the editing process.

    If you're going to submit a PR for typo fixes, please be measured in doing so by collecting several small changes into a single PR (in separate commits). Or, just don't even worry about them for now, because we'll get to them later. I promise.


    Please type "I already searched for this issue":

    I already searched for this issue

    Edition: (pull requests not accepted for previous editions) 2

    Book Title:

    Chapter: 1 & 2 & A & 4 & 5

    Section Title: many

    Topic:


    I found an issue of sample code, but found that has been pointed in https://github.com/getify/You-Dont-Know-JS/pull/1770, so I didn't fix.

    for second edition 
    opened by dev-itsheng 3
  • Replace the

    Replace the "As mentioned earlier" part in ch1.md

    Maybe I'm wrong (hope I'm not), I don't remember any mentions about an array type at that point of the book. I've tried to find it, but I found nothing. It might be an artefact of the original book (the 1st edition).

    So I'd replace the "As mentioned earlier" part with something not confusing. I'm not a native English, so probably you have a better idea for the replacement.

    "I already searched for this issue"

    Edition: 2nd

    Book Title: You Don't Know JS Yet: Get Started

    Chapter: 2

    Section Title: Values

    Topic: Arrays And Objects

    for second edition 
    opened by SiarheiBobryk 0
  • Code generation and memory allocation

    Code generation and memory allocation

    Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line).


    Please type "I already searched for this issue": I already searched for this issue

    Edition: (1st or 2nd) 2nd

    Book Title: Scope & Closures

    Chapter: 1 & 2

    Section Title: Compiling Code

    Question:

    Thanks for this excellent book, I'm enjoying every line of it! Could you please address a question?

    In Chapter 1, section Compiling Code states: "The JS engine takes the just described AST for var a = 2; and turns it into a set of machine instructions to actually create a variable called a (including reserving memory, etc.), and then store a value into a."

    However, in chapter 2, section A Conversation Among Friends, memory allocation seems to be described as happening at execution time: "Encountering var students, Compiler will ask Scope Manager to see if a variable named students already exists for that particular scope bucket. If so, Compiler would ignore this declaration and move on. Otherwise, Compiler will produce code that (at execution time) asks Scope Manager to create a new variable called students in that scope bucket."

    Could you please clarify this apparent contradiction? Is it the case that when the compiler reserves memory, it reserves it as an empty, anonymous slot that will be later filled by the scope manager with the actual variable name and variable value? If yes, how does this mapping between reserved memory and actual allocation happen? Could it happen that the reserved memory is not large enough for the actual value that has to be stored? How would JS solve this problem?

    Many thanks, Manu

    question 
    opened by nunesky 3
  • view shallow copy output

    view shallow copy output

    Just a addition so the reader knows what the output of this shallow copy is using the spread operator. As I myself was wondering if there is a difference between var arrCopy = [ ...arr ]; or arrCopy = arr; Specifically quoting these guidelines regarding typos:

    I already searched for this issue

    Edition: (pull requests not accepted for previous editions) 2 Book Title: get-started Chapter: 3 Section Title: Iterables Topic:

    enhancement 
    opened by Jeroendevr 1
  • fix: more complete statement for Map

    fix: more complete statement for Map

    Please type "I already searched for this issue": I already searched for this issue Edition: (pull requests not accepted for previous editions) 2-nd edition Book Title: Get Started Chapter: Chapter 3: Digging to the Roots of JS Section Title: Iteration -> Iterables Topic: Fixed statement about Map keys.

    question for second edition 
    opened by DBadalyan 2
Owner
Kyle Simpson
I like to explore JS and FP techniques. Helping build a culture of engineering excellence for my employer.
Kyle Simpson
This is a single page web application that keeps tracks of books. Book details captured are the book title, author and ISBN. User can add a book, view a list of books and also remove any un wanted books.

Project Name This is a single page web application that keeps tracks of books. Book details captured are the book title, author and ISBN. User can add

Olivier 6 Nov 20, 2022
Well Read is a website for tracking your reading of long book series.

Read without losing the plot. Well Read helps you organize your notes about books you're reading, so you're never lost when starting a new volume.

null 3 Dec 15, 2022
Awesome-book is an online library website where a user can store a collection of books. Different book can be added and removed. Built with JavaScript using Dom

Awesome-book Description Awesome-book is an online library website where a user can store a collection of books. Differents book can be added and remo

tarike bouari 8 Sep 9, 2022
A single-page application that allows users to keep track of their books. Users can add the book details (book title and author) and also, and the books can also be removed. Built with JavaScript, HTML, and CSS

Project Name Awesome book with ES6 Description the project. This is a single page application that allows users to keep track of their books. Users ca

Micheal Oguntayo 4 Oct 13, 2022
:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

TypeScript Deep Dive I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack

Basarat Ali Syed 18.7k Jan 4, 2023
The Bookstore is a website that allows the user to :display a list of books , Add a book and remove a selected book.

Book Store The Bookstore is a website that allows the user to : -Display a list of books. -Add a book. -Remove a selected book. Built With ?? Basic CS

Nedjwa Bouraiou 4 Sep 6, 2022
BookStore is a website that allows a given user to view a list of books, to add a new book and remove a given book.

Project Name : BookStore CMS BookStore is a website that allows a given user to view a list of books, to add a new book and remove a given book. In or

Chris Siku 10 Aug 22, 2022
This is an app that displays a list of books, allow users add a book and remove a selected book.

BookStore This is an app that displays a list of books, allow users add a book and remove a selected book. Built With HTML CSS -React -Redux -JavaScri

ABDUL ALI 5 Jul 22, 2022
The Bookstore is a website where the user can display a list of books, add a book by providing a title, an author, and selecting from the categories, and remove a selected book.

Bookstore The Book Store is a website where the user can display a list of books, add a book and remove a selected book. Microverse's Bookstore API wa

Virag Kormoczy 9 Jan 1, 2023
Awesome Books project : An online Book Library. Storing book information using local storage and displaying it as a list on HTML page

This is project is my based on building an online Book Library. Storing book information using local storage and displaying it as a list on html page

Richard Chileya 7 Nov 11, 2022
Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.

twitter-text This repository is a collection of libraries and conformance tests to standardize parsing of Tweet text. It synchronizes development, tes

Twitter 2.9k Jan 8, 2023
Fuck Twitter NFTs - Userscript to delete or block all occurances of NFT Users on Twitter

FuckTwitterNFTs Fuck Twitter NFTs - Userscript to delete or block all occurances of NFT Users on Twitter Userscript will by default, attempt to delete

Blumlaut 1 Jan 20, 2022
Twitter bot to find what song is playing in a given uploaded twitter video.

what-song-is-this Twitter bot to find what song is playing in a given uploaded twitter video. How to setup. yarn install How to run. via npm script ya

Akinwande Akinboluwarin 17 Dec 11, 2022
A Twitter filtered search to only get the live broadcasts hosted on Twitter itself, Built using Vanilla JS and Node.js

Twitter Broadcasts Search A Twitter filtered search to only get the live broadcasts hosted on Twitter itself, Built using Vanilla JS and Node.js. Live

Mohammad Mousad 2 Oct 6, 2022
Reference for How to Write an Open Source JavaScript Library - https://egghead.io/series/how-to-write-an-open-source-javascript-library

Reference for How to Write an Open Source JavaScript Library The purpose of this document is to serve as a reference for: How to Write an Open Source

Sarbbottam Bandyopadhyay 175 Dec 24, 2022
It maintains my version of js notes which I learned from the famous Namaste Javascript Youtube Series by Akshay Saini.

Welcome to Namaste Javascript Notes ?? ❓ what it is This repo maintains my version of javascript notes which I learned from the famous Namaste Javascr

Alok Raj 682 Jan 4, 2023
Code accompanying my illustrated Data structures video series on YouTube

Code accompanying my illustrated Data structures video series on YouTube

Kamran Ahmed 122 Dec 10, 2022
This is a Netflix clone where you can watch movies or series

Netlfix Clone This is a Netflix clone where you can watch movies or series. Visit Now ?? Things I Implemented SignIn/SignUp Movie/Series Filter Watch

Neelesh Singh 3 Dec 1, 2022
Use your web inspector to hack your way through a series of challenges.

hacker-challenge Use your inspector to hack your way through a series of challenges. Made for those who are new to the inspector. A web inspector is a

jessicard 0 Jun 17, 2022