Mistaken example?
nmaxcom opened this issue · comments
Hi. At the end of the 2nd chapter you provide the following piece of code saying:
When the items variable is changed to reference another list of items, we’re in for a world of hurt—the todo API still works with the value items used to have, but items is referencing something else now.
var items = ['a', 'b', 'c']
var todo = checklist(items)
todo.check()
console.log(items)
// <- ['b', 'c']
items = ['d', 'e']
todo.check()
console.log(items)
// <- ['d', 'e'], would be ['c'] if items had been constant
function checklist(items) {
return {
check: () => items.shift()
}
}
IMHO items
and the checklist
function are just forming a closure. So once that todo
var is created and items
is referenced to another thing, it doesn't matter what is done to items
, it's irrelevant to the code.
I'm just a hobbyist so I thought someone should take a look at it.
@nmaxcom You're correct. The point I'm making here is that, if items
were a const
binding, you wouldn't be able to do items = ['d', 'e']
down the line. Thus, if items
were const
, it'd have a reference to the same array in the context of the checklist
scope and the parent scope.
It's not an unsolvable problem, but you have to make sure the binding didn't change in order to keep treating the two as if they were the same. With const
, in contrast, you can rest assured that the binding reference is the same as the one you passed down earlier, because you can't change it.