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