getify / You-Dont-Know-JS

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

Scope & Closures/Appendix A/Anonymous vs. Named Functions: Error in code example #1651

Closed nmonastyrskyi closed 4 years ago

nmonastyrskyi commented 4 years ago

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

Edition: 2nd

Book Title: Scope & Closures

Chapter: Appendix A

Section Title: Anonymous vs. Named Functions / Explicit or Inferred Names

Problem:

There are two blocks of code and there is an error in the first one:

btn.addEventListener("click",function(){
    setTimeout(function(){
        ["a",42].map(function(v){
            console.log(v.toUpperCase());
        });
    },100);
});
// Uncaught TypeError: Cannot read property
// 'toUpperCase' of null
//     at myProgram.js:4
//     at Array.map (<anonymous>)
//     at myProgram.js:3

Surprisingly as it may seem, the problem is in the example of the error:

When we click on the btn element. We have this error (in the book): Pay attention to the first two lines

// Uncaught TypeError: Cannot read property
// 'toUpperCase' of null
//     at myProgram.js:4
//     at Array.map (<anonymous>)
//     at myProgram.js:3

But the real error should look like this:

// Uncaught TypeError: v.toUpperCase is not a function
//     at myProgram.js:4
//     at Array.map (<anonymous>)
//     at myProgram.js:3

It is because in the array ["a",42] second value is 42. But in the book's example it behaves like the the second value in the array is null

By the way, the second example with Named Functions is ok:

btn.addEventListener("click",function onClick(){
    setTimeout(function waitAMoment(){
        ["a",42].map(function allUpper(v){
            console.log(v.toUpperCase());
        });
    },100);
});
// Uncaught TypeError: v.toUpperCase is not a function
//     at allUpper (myProgram.js:4)
//     at Array.map (<anonymous>)
//     at waitAMoment (myProgram.js:3)
getify commented 4 years ago

Ahh, I had changed the example (the kind of error being thrown) while writing this, and forgot to update the previous snippet's comment with the correct error message text. Good catch, thanks.