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+
211let age = 20 ; // Declare and initialize variable
312age = 30 ; // Update the value
413
5- // Using const (for constant values that should not change)
6- // NOTE: It's better to use all letters upppercase when using constants
714const PI = 3.14 ; // Declare and initialize constant
815
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:
1217
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 ;
1422
15- // Block scope with let and const
23+ // Block scope: only var is accessable outside the block
1624if ( true ) {
25+ var accessable = "I am accessable" ;
1726 let blockScoped = "I exist only inside this block" ;
1827 const constantScoped = "Also block-scoped" ;
19- console . log ( blockScoped ) ; // Works here
28+ console . log ( blockScoped , constantScoped , accessable ) ; // Works here
2029}
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 ) ;
2638}
27- console . log ( functionScoped ) ; // Works here (if not inside a function)
39+ console . log ( d , e , f ) ; // Error
2840
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+ */
3347
3448// Example of valid variable names:
3549let userName ;
@@ -39,7 +53,7 @@ let _count;
3953// Example of invalid variable name:
4054// let 1stName; // Syntax Error
4155
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)
4357function wrongExample ( ) {
4458 someVar = 10 ; // Declares a global variable unintentionally
4559}
0 commit comments