You Don't Know JS: Scope & Closures (#2) by Kyle Simpson.

How scope and closures work in JS. What is Hoisting?

Polish: Tajniki języka JavaScript. Zakresy i domknięcia"

book photo

Book public Github repo #

Please remember that all "You don't know JS" books are available on Github. Please support Kyle Simpson on Patreon.

First book #

Review of the first book in the series (with links to other books for beginners)

About the book #

It's not a book for beginners.

The book is for you if you've used JS for some time. You want to dig dipper, understand some parts of the language that are still confusing. Maybe how does the var work? What is hoisting? What are closures? It's a great book to get a deeper understanding, and I would recommend it for at least Advanced Beginners.

I've learned that I can use blocks to make sure Garbage Collector can pick up objects that would be otherwise preserved because of a closure.

var reallyBigData = getProductsListData();

var finalPrice = doSomethingWithData(reallyBigData);

const plusButton = document.getElementById("plus_button");

plusButton.addEventListener(
"click",
function clickCallback(e) {
// knows about reallyBigData
addItemRequest();
},
/*capturingPhase=*/ false
);

The problem with this code is that reallyBigData can be kept in memory because it's in the closure of clickCallback. It's implementation-dependent, but if you stumble upon it then it can be solved by adding a block:

{
var reallyBigData = getProductsListData();

var finalPrice = doSomethingWithData(reallyBigData);
}

const plusButton = document.getElementById("plus_button");

plusButton.addEventListener(
"click",
function clickCallback(e) {
addItemRequest();
},
/*capturingPhase=*/ false
);

Hoisting from my point of view #

I can still recommend my posts about hoisting for you to have another point of view:



Share on Hacker News
Share on LinkedIn


← Home


Want to learn more?

Sign up to get a digest of my articles and interesting links via email every month.

* indicates required

Please select all the ways you would like to hear from Krzysztof Kula:

You can unsubscribe at any time by clicking the link in the footer of my emails.

I use Mailchimp as a marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.