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)

10th Nov 2024, 12:24 AM
♬Astro-GingyFlake🇹🇷
♬Astro-GingyFlake🇹🇷 - avatar
7 Réponses
+ 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/
10th Nov 2024, 1:44 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 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.
10th Nov 2024, 2:44 AM
Gulshan Mahawar
Gulshan Mahawar - avatar
+ 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
10th Nov 2024, 2:07 AM
Bob_Li
Bob_Li - avatar
+ 3
Any modern JavaScript should use "let". Don't bother getting to know what "var" is for. I've never used it since 2019
10th Nov 2024, 9:54 PM
RuntimeTerror
RuntimeTerror - avatar
+ 1
Thank you, I was just curious on what the difference was
10th Nov 2024, 10:03 PM
♬Astro-GingyFlake🇹🇷
♬Astro-GingyFlake🇹🇷 - avatar
+ 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
10th Nov 2024, 10:41 PM
Bob_Li
Bob_Li - avatar
+ 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.
11th Nov 2024, 3:01 PM
RANA
RANA - avatar