getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
178.28k stars 33.42k forks source link

Scope & Closures, Ch 3- Different behavior observed than stated "can't reassign the BLUE(2) special parameter" #1687

Closed vikrantuk closed 3 years ago

vikrantuk commented 3 years ago

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

Edition: (1st or 2nd) 2nd

Book Title: You Don't Know JS Yet: Scope & Closures

Chapter: The Scope Chain

Section Title: Copying Is Not Accessing

Problem: Book states that-

Another "But...!?" you may be about to raise: what if I'd used objects or arrays as the values instead of the numbers (112358132134, etc.)? Would us having references to objects instead of copies of primitive values "fix" the inaccessibility?

No. Mutating the contents of the object value via a reference copy is not the same thing as lexically accessing the variable itself. We still can't reassign the BLUE(2) special parameter.

But on running this code in chrome browser:

var special = 42;

function lookingFor(special) {
    var another = {
        special: special
    };

    function keepLooking() {
        var special = 3.141592;
        console.log(special);
        console.log(another.special);  // Ooo, tricky!
        console.log(window.special);
        another.special.a = 23;
    }

    keepLooking();
    console.log(special);
}

lookingFor({a:54});

Generates output:

3.141592
{a: 54}
42
{a: 23}

Here special from lookingFor function gets changed to update value of a to 23. Which goes against stated lines in book: "We still can't reassign the BLUE(2) special parameter."

getify commented 3 years ago

That's not re-assigning the BLUE special... that's mutating the contents inside the object that the BLUE special points to, by virtue of a copied reference to that object. Those are entirely different things. There is absolutely no way to access the shadowed BLUE special as a lexical identifier, meaning there's no way to re-assign it.

vikrantuk commented 3 years ago

@getify Thanks for the clarification..