getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
178.87k stars 33.44k forks source link

Arrays And Objects #1609

Closed fromxt closed 4 years ago

fromxt commented 4 years ago

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

Edition: 2nd**

Book Title: You Don't Know JS Yet (book series) - 2nd Edition**

Chapter: Chapter 2: Surveying JS**

Section Title:Arrays And Objects**

Question: When ran the following code in the Chrome Console,

name = {
    first: "Kyle",
    last: "Simpson",
    age: 39,
    specialties: [ "JS", "Table Tennis" ]
};

console.log(`My name is ${ name.first }.`);

I was a bit confused at the result , expected to My name is Kyle ,but the actual output is My name is undefined. Is the name also reserve keywords in JS? Thanks

getify commented 4 years ago

Sorry for the confusion. Those snippets aren't necessarily meant to be typed directly into a program or console. They're illustrative.

In this particular case, yes, name in the global scope is a very special corner case in the browser. I cover why that weirdness is happening over in another book, here:

https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch4.md#whats-in-a-window-name

I suppose maybe that variable should have been called record or even myName, to avoid this accidental overlap.