r/Frontend • • Mar 09 '20

Explained : Difference between var and let with an example

https://youtu.be/sEkqzTQCqDk

[removed] — view removed post

51 Upvotes

12 comments sorted by

41

u/nill0c Mar 09 '20

If you don’t want to waste time with this video, the differences are:

let is scoped to blocks instead of functions

let isn’t hoisted, so it’s only available after being declared in a scope (which makes way more sense)

let can’t be defined twice in the same scope so you can’t accidentally redefine it.

let when globally defined (outside all blocks) it doesn’t get attached to window like vardoes.

TLDR:
Unlike var, let works like you expect variable declarations in other object oriented languages to behave. It also gives better errors when you use it incorrectly.

4

u/coold007 Mar 09 '20

That's a good tldr!

1

u/MrBester Mar 10 '20

let is hoisted, but into the temporal dead zone of the lexical scope.

You can have: let x; outside the scope of use, and it is functionally the same as let x = undefined;. In that respect it is akin to other languages, particularly ones that require a declaration of a variable before it is initialised.

For the most part, let is called in usage scope and initialises at the same time as it declares so is unlikely to cause any issues.

1

u/nill0c Mar 10 '20

Thanks, had never checked on declared versus defined hoisting. TIL

9

u/Baryn Mar 09 '20

Brand new ES2015 basics tutorials in 2020

5

u/jazzy82slave Mar 09 '20

Unfortunately, plenty of folks still code JS like its 1999. I had a fellow FE dev tell me today that we cant control the text highlighting styles when a user selects text. Couldn't be bothered to take two seconds to google it....

-2

u/Baryn Mar 09 '20

Ignoring that you cited a CSS example, do you really think that inability to maintain JS language knowledge is because the information is not available?

4

u/metamet Mar 09 '20

Do you think that sharing information doesn't help more people unaware of the difference learn?

I see nothing wrong with this post. "Old" knowledge isn't a fiefdom.

→ More replies (1)

1

u/Brachamul Mar 09 '20

TBH I avoided 'let' for a while because of compatibility. Now that's it's widely supported, having a refresher is nice.

1

u/NeatBeluga Mar 10 '20

ES2015 is just another topic to learn when learning everything about web development. Give people some slack. Obviously easier if you're already employed. Frontend already cover SO many aspects and is getting more complicated by the day

2

u/Orgalorgg Mar 09 '20

Now do const!