1
- // variables.js
2
-
3
1
// Using let (recommended for variables that can change)
4
- let age = 20 ; // Declare and initialize variable
5
- age = 30 ; // Update the value
6
-
2
+ let age = 20 ; // Declare and initialize variable
3
+ age = 30 ; // Update the value
7
4
8
5
// Using const (for constant values that should not change)
9
- const pi = 3.14 ; // Declare and initialize constant
10
-
6
+ // NOTE: It's better to use all letters upppercase when using constants
7
+ const PI = 3.14 ; // Declare and initialize constant
11
8
12
9
// Using var (old way, avoid if possible)
13
10
// var declarations are function-scoped and can lead to unexpected behavior
14
11
var name = "John" ;
15
12
16
-
17
13
// Variable scope examples:
18
14
19
15
// Block scope with let and const
20
16
if ( true ) {
21
17
let blockScoped = "I exist only inside this block" ;
22
18
const constantScoped = "Also block-scoped" ;
23
- console . log ( blockScoped ) ; // Works here
19
+ console . log ( blockScoped ) ; // Works here
24
20
}
25
21
// console.log(blockScoped); // Error: blockScoped is not defined
26
22
27
-
28
23
// var is function scoped, not block scoped
29
24
if ( true ) {
30
25
var functionScoped = "I exist inside the function or globally" ;
31
26
}
32
- console . log ( functionScoped ) ; // Works here (if not inside a function)
33
-
27
+ console . log ( functionScoped ) ; // Works here (if not inside a function)
34
28
35
29
// Variable naming rules:
36
30
// - Can contain letters, digits, underscores, and dollar signs
@@ -45,12 +39,9 @@ let _count;
45
39
// Example of invalid variable name:
46
40
// let 1stName; // Syntax Error
47
41
48
-
49
42
// Variables declared without let, const, or var become global (avoid this)
50
43
function wrongExample ( ) {
51
- someVar = 10 ; // Declares a global variable unintentionally
44
+ someVar = 10 ; // Declares a global variable unintentionally
52
45
}
53
46
wrongExample ( ) ;
54
- console . log ( someVar ) ; // 10 (global scope)
55
-
56
-
47
+ console . log ( someVar ) ; // 10 (global scope)
0 commit comments