r/learnjavascript • • Oct 26 '20

Javascript string 🔥

193 Upvotes

31 comments sorted by

View all comments

47

u/MrMimmet Oct 26 '20

You should really avoid using 'var' to declare your variables.

21

u/I-DONT-WANT-GOLD Oct 26 '20

Why?

0

u/[deleted] Oct 26 '20

[deleted]

11

u/I-DONT-WANT-GOLD Oct 26 '20

Great, thank you very much!

0

u/[deleted] Oct 26 '20

[deleted]

4

u/[deleted] Oct 26 '20

It’s my understanding that you should use const by default for readability. The idea is if another dev is looking at your code and sees “let” they will know that variable will be reassigned later in the code. Makes the program easier to understand at a glance.

1

u/beelzebut Oct 27 '20

Using const by default is good practice. Why would you use let for variables that do not need to be reassigned?

13

u/scandii Oct 26 '20 edited Oct 27 '20

downvoted for asking a question... this sub.

let has a block scope, i.e lives ans dies in the scope it is declared, whereas var is global or if in a function has a function scope and can be used anywhere.

this can lead to some nasty side effects and is as such not recommended.

6

u/I-DONT-WANT-GOLD Oct 26 '20

Yeah, sorry if it was such a dumb question, but I was genuinely asking. Thank you!

15

u/scandii Oct 26 '20

there are no dumb questions only stupid answers.

5

u/Hate_Feight Oct 26 '20

Only stupid people who fail to ask them...

1

u/beelzebut Oct 27 '20

You actually gave him a bad answer tho

4

u/awkreddit Oct 26 '20

Var is not global at all, var is scoped to the function, let is scoped to the block.

4

u/[deleted] Oct 26 '20

It stimulates browsers' hunger for ram

2

u/I-DONT-WANT-GOLD Oct 26 '20

Wow, that is something I would never have imagined. Thank you!

7

u/mothzilla Oct 26 '20

The reply was nonsense, but most browsers support let and const, and if not (ie you want to support IE6) you can use a code transpiler.

var has subtle scoping issues as pointed out by /u/0xc0ba17.

-3

u/EIGRP_OH Oct 26 '20 edited Oct 27 '20

i.e lives ans dies in the scope it is declared, whereas var is global and can be used anywhere.

Var also puts variables on the global Window object where Let and Const don't.

EDIT: for those downvoting this can you explain why I’m wrong instead of downvoting? I’d genuinely like to know.

1

u/awkreddit Oct 27 '20

Var is not global

2

u/EIGRP_OH Oct 27 '20

I should have mentioned that outside of a function and if it’s within global scope. Not that var is inherently global. My bad