JavaScript Var vs Let

The cluster focuses on discussions about the scoping differences between function-scoped 'var' and block-scoped 'let'/'const' in JavaScript, including debates on the benefits of block scoping, reasons to avoid 'var', and examples of scoping issues in loops and blocks.

➡️ Stable 0.5x Programming Languages
2,513
Comments
20
Years Active
5
Top Authors
#6828
Topic ID

Activity Over Time

2007
1
2008
19
2009
26
2010
55
2011
126
2012
116
2013
138
2014
138
2015
202
2016
151
2017
156
2018
105
2019
159
2020
156
2021
216
2022
183
2023
216
2024
140
2025
205
2026
5

Keywords

OP JS BTW JavaScript ES6 freecodecamp.org LOW i.e QrCode obj.foo var scoping scoped block scope variable let function javascript qr

Sample Comments

jasondenizac • Oct 2, 2012 • View on HN

new scoping for `var`? Like the block-scoped `let`?

tuukkah • Feb 26, 2023 • View on HN

... because var is function-scoped, not block-scoped like let.

chrisseaton • Oct 24, 2016 • View on HN

How is having var be function scoped instead of block scoped a useful feature?

atonse • May 15, 2015 • View on HN

No, because you have to use the new 'let' keyword to get block scoping. So you have to opt-in to it.

secoif • Nov 26, 2012 • View on HN

You want block scoping. Block scoping is coming in ES6 with the let keyword.

woojoo666 • May 3, 2022 • View on HN

`var` is function scoped, `let` is block scoped.

taco_emoji • Jun 15, 2015 • View on HN

It's the same reason that, yes, you can put "var x" in an if-block, but it's bad practice because it misleads the reader (even one who knows that Javascript is function scoped) into thinking that x is block-scoped.

ufo • Jul 8, 2012 • View on HN

Err, sounds like a weird thing to do, and as they mentioned, is more likely just a limitation of their inferrence engine. Preventing variable shadowing leaks implementation details from inside functions/blocks and mos tlanguages do just fine with appropriate warnings and so on.

tengbretson • Jun 26, 2022 • View on HN

How about don't use let or var declarations at all?

cwmma • Mar 6, 2020 • View on HN

the one thing that annoys me about let/const that leads to me occasionally using var is that with var you can declare a variable in a try block and then use it afterwards, instead I have to declare a let outside the try or put way more then I want to in the try.