Kula.blog

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

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:


← Home