|
2 | 2 |
|
3 | 3 | ## What is the difference between var, let and const?
|
4 | 4 |
|
| 5 | +### var |
| 6 | +Scope: Function-scoped. If declared inside a function, it is accessible within that function. If declared outside, it is globally scoped. |
| 7 | +Hoisting: Variables declared with var are hoisted to the top of their scope and initialized with undefined. |
| 8 | +Re-declaration: Can be re-declared within the same scope without errors. |
| 9 | + |
| 10 | +### let |
| 11 | +Scope: Block-scoped. It is only accessible within the block (e.g., {}) where it is declared. |
| 12 | +Hoisting: Variables declared with let are hoisted but not initialized. Accessing them before declaration results in a ReferenceError. |
| 13 | +Re-declaration: Cannot be re-declared within the same scope. |
| 14 | + |
| 15 | +### const |
| 16 | +Scope: Block-scoped, similar to let. |
| 17 | +Hoisting: Variables declared with const are hoisted but not initialized. Accessing them before declaration results in a ReferenceError. |
| 18 | +Re-declaration: Cannot be re-declared within the same scope. |
| 19 | +Assignment: Must be initialized at the time of declaration and cannot be reassigned. However, if the variable is an object or array, the contents can be modified. |
| 20 | + |
| 21 | +### Example |
| 22 | +```js |
| 23 | +function example() { |
| 24 | + var x = 1; |
| 25 | + if (true) { |
| 26 | + var x = 2; // Same variable, re-declared |
| 27 | + console.log(x); // 2 |
| 28 | + } |
| 29 | + console.log(x); // 2 |
| 30 | + |
| 31 | + let y = 1; |
| 32 | + if (true) { |
| 33 | + let y = 2; // Different variable, block-scoped |
| 34 | + console.log(y); // 2 |
| 35 | + } |
| 36 | + console.log(y); // 1 |
| 37 | + |
| 38 | + const z = 1; |
| 39 | + if (true) { |
| 40 | + const z = 2; // Different variable, block-scoped |
| 41 | + console.log(z); // 2 |
| 42 | + } |
| 43 | + console.log(z); // 1 |
| 44 | +} |
| 45 | +``` |
| 46 | + |
5 | 47 | ## Can you explain `Closures` to me?
|
6 | 48 | [Mozilla Developer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
|
7 | 49 |
|
@@ -106,4 +148,4 @@ compose(
|
106 | 148 |
|
107 | 149 | ![observables][observables]
|
108 | 150 |
|
109 |
| -[observables]: ./assets/javascript-essentials-observables.png "Observables" |
| 151 | +[observables]: ./assets/javascript-essentials-observables.png "Observables" |
0 commit comments