0
What is different between var and let in JavaScript
*I’m learning JavaScript and I’m confused between `var` and `let`. Can someone explain the difference between them with examples? Also, when should I use one over the other?
3 odpowiedzi
+ 6
https://www.w3schools.com/js/js_let.asp
This explains the purpose of both with examples
0
Using `var` hoists your variables at the top of your function as a function-scoped variable, accessible from anywhere from inside the function
Example:
```
function exampleVar() {
console.log(x); // undefined, not ReferenceError (hoisted but undefined)
var x = 10;
if (true) {
var x = 20; // same variable (function-scoped)
console.log(x); // Output: 20
}
console.log(x); // Output: 20
}
exampleVar();
```
Using `let` will declare a block-scoped variable in its scope without hoisting it
Example:
```
function exampleLet() {
console.log(y); // ReferenceError
let y = 10;
if (true) {
let y = 20; // Different variable (block-scoped)
console.log(y); // Output: 20
}
console.log(y); // Output: 10
}
exampleLet();
```
Always use let unless you know well what you're doing
0
Thank you Man