0
What's the difference between variable declaration in JavaScript?!
In JavaScript, there is two types of variable declarations that literally have no difference. Can you tell me what the difference is? (let x=1, and var x=1)
7 Answers
+ 5
The keywords let and var both declare new variables in JavaScript. The difference between let and var is in the scope of the variables they create:
Variables declared by let are only available inside the block where theyāre defined.
Variables declared by var are available throughout the function in which theyāre declared.
Source:
https://sentry.io/answers/difference-between-let-and-var-in-javascript/
+ 7
In addition to scope of variable and hoisting, you can redeclare a variable using var within same scope which may lead to bug if you accidentally overwrite variables.
But redeclare a variable using `let` keyword is not allowed ,which prevent accidental overwriting.
+ 5
As Wong Hei Ming pointed out, scoping is one of the main difference. The use of let is preferred because it is better constrained and does not produce unexpected behavior.
Another difference is let is not hoisted while var is hoisted. Hoisted might seem better but it's not. It can also produce unexpected behavior.
So use let, don't use var.
Also watch out for variables without const, let or var...
https://stackoverflow.com/questions/6888570/declaring-variables-without-var-keyword
+ 3
Any modern JavaScript should use "let".
Don't bother getting to know what "var" is for. I've never used it since 2019
+ 1
Thank you, I was just curious on what the difference was
+ 1
ā¬Astro-GingyFlakeš¹š·
a lot of people learn from old books and tutorials that used var. And most are unaware of its design flaws.
var is when the phrase "It's a feature, not a bug" is used when your code becomes quirky.
more about let and var:
https://www.simplilearn.com/tutorials/javascript-tutorial/let-in-javascript
+ 1
_VarĀ isĀ availableĀ throughoutĀ theĀ entireĀ function,Ā evenĀ beforeĀ itĀ isĀ declared,Ā becauseĀ itĀ isĀ function-scoped.
BecauseĀ letĀ isĀ block-scoped,Ā itĀ canĀ onlyĀ beĀ usedĀ insideĀ theĀ blockĀ {}Ā whereĀ itĀ isĀ defined,Ā suchĀ asĀ withinĀ anĀ ifĀ statementĀ orĀ aĀ loop.