getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
179.26k stars 33.48k forks source link

Function parameters are "let" scoped, not "var"? #1795

Closed phantomwhale closed 2 years ago

phantomwhale commented 2 years ago

I already searched for this issue

Edition: (2nd)

Book Title: get started

Chapter: 2

https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch2.md#L281

Question:

Forgive me if I'm wrong (because I don't know JS yet!) but it seems that myname, the function parameter, behaves as let declared, not var declared.

Not sure if the same applies to the hello function though, as I've only really seen them defined at the most outer scope of a JS file.

Or did I miss something in the explanation (I've gone through it twice!)

aayuushh365 commented 2 years ago

The difference between var and let is, var is function scoped. i.e. var can only be used inside a function. on the other hand let is used as block -scope. i.e. it can be accessed inside a block Also, it is important to note that let cannot be redeclared in a program which is a good thing. Prevents confusion. whereas var can be redefined. So, you can use var or let any of these. but make sure whether you have to redefine the variables or not.

you can use refer here - https://www.programiz.com/javascript/let-vs-var

getify commented 2 years ago

The book text is correct, this is not a mistake.

cyberGHostJs commented 2 years ago

@aayuushh365 said it all.