Skip to content

Commit 793c32e

Browse files
authored
Update javascript-essentials.md with var, let and const answer
1 parent 0c5c882 commit 793c32e

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

javascript/javascript-essentials.md

+43-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,48 @@
22

33
## What is the difference between var, let and const?
44

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+
547
## Can you explain `Closures` to me?
648
[Mozilla Developer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
749

@@ -106,4 +148,4 @@ compose(
106148

107149
![observables][observables]
108150

109-
[observables]: ./assets/javascript-essentials-observables.png "Observables"
151+
[observables]: ./assets/javascript-essentials-observables.png "Observables"

0 commit comments

Comments
 (0)