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?

3rd Jul 2025, 3:19 PM
illegalperson46
illegalperson46 - avatar
3 odpowiedzi
+ 6
https://www.w3schools.com/js/js_let.asp This explains the purpose of both with examples
3rd Jul 2025, 3:30 PM
Afnan Irtesum Chowdhury
Afnan Irtesum Chowdhury - avatar
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
6th Jul 2025, 6:58 AM
Vaibhav
Vaibhav - avatar
0
Thank you Man
13th Jul 2025, 4:25 PM
illegalperson46
illegalperson46 - avatar