|
1 | | -# 2. JavaScript Variables |
2 | | -*** |
3 | | - |
4 | | -**Example 1: Declaring and Assigning Variables** |
5 | | - |
6 | | -```javascript |
7 | | -// Using 'let' to declare and assign a variable |
8 | | -let name = "John"; |
9 | | -let age = 30; |
10 | | - |
11 | | -// Using 'const' for a constant variable |
12 | | -const pi = 3.14; |
13 | | -``` |
14 | | - |
15 | | -In this example, we declare a variable named `name` and assign the string value "John" to it. We also declare a variable `age` and assign the number 30 to it. The `const` keyword is used to declare a constant variable `pi` with a value of 3.14, which cannot be reassigned. |
16 | | - |
17 | | -**Example 2: Updating Variables** |
18 | | -```javascript |
19 | | -let count = 5; |
20 | | -count = count + 1; // Updating the 'count' variable |
21 | | -``` |
22 | | - |
23 | | -Here, we declare a variable `count` with an initial value of 5. We then update the variable's value by adding 1 to it. |
24 | | - |
25 | | -**Example 3: Data Types** |
26 | | -```javascript |
27 | | -let message = "Hello, world!"; |
28 | | -let isRaining = true; |
29 | | -let numbers = [1, 2, 3, 4, 5]; |
30 | | -let person = { name: "Alice", age: 25 }; |
31 | | -``` |
32 | | - |
33 | | -In this example, we declare variables with different data types: |
34 | | -- `message` is a string. |
35 | | -- `isRaining` is a boolean. |
36 | | -- `numbers` is an array. |
37 | | -- `person` is an object. |
38 | | - |
39 | | -**Example 4: Variable Naming and Scope** |
40 | | -```javascript |
41 | | -let globalVar = "I'm global"; |
42 | | - |
43 | | -function exampleScope() { |
44 | | - let localVar = "I'm local"; |
45 | | - console.log(globalVar); // Accessible inside the function |
46 | | - console.log(localVar); // Accessible within the function |
47 | | -} |
48 | | - |
49 | | -console.log(globalVar); // Accessible globally |
50 | | -// console.log(localVar); // Results in an error - 'localVar' is not defined outside the function |
51 | | -``` |
52 | | - |
53 | | -In this example, we declare two variables: `globalVar` and `localVar`. `globalVar` is declared in the global scope and can be accessed both inside and outside the function. `localVar` is declared within the `exampleScope` function and is only accessible within that function, demonstrating the concept of variable scope. |
54 | | - |
55 | | -**Example 5: Hoisting** |
56 | | -```javascript |
57 | | -console.log(x); // undefined (hoisted but not initialized) |
58 | | -var x = 5; |
59 | | - |
60 | | -// console.log(y); // ReferenceError (let and const are not hoisted) |
61 | | -let y = 10; |
62 | | -``` |
63 | | - |
64 | | -In this example, the `var` variable `x` is hoisted to the top of the current scope, but it's not initialized yet, so it's `undefined`. The `let` variable `y` is not hoisted, and attempting to access it before declaration results in a `ReferenceError`. |
65 | | - |
66 | | -These examples illustrate how to declare, assign, and use variables in JavaScript, covering various data types, scoping, and hoisting. Understanding these concepts is essential for working with variables effectively in JavaScript. |
67 | | - |
68 | | - |
| 1 | +# JavaScript Variables |
| 2 | + |
| 3 | +## 1. Introduction to Variables |
| 4 | + |
| 5 | +### Definition |
| 6 | +- A variable is a named storage location in computer memory |
| 7 | +- Used to store and manage data during program execution |
| 8 | +- Acts as a container that holds a specific value which can be modified or referenced |
| 9 | + |
| 10 | +### Key Characteristics |
| 11 | +- Provides a way to label and store data |
| 12 | +- Enables dynamic data manipulation |
| 13 | +- Supports various data types and scopes |
| 14 | + |
| 15 | +## 2. Variable Declaration Methods |
| 16 | + |
| 17 | +### 1. `var` (Legacy Declaration) |
| 18 | +```javascript |
| 19 | +var oldStyleVariable = "I'm an old school variable"; |
| 20 | +``` |
| 21 | +#### Characteristics |
| 22 | +- Function-scoped or globally-scoped |
| 23 | +- Can be re-declared and updated |
| 24 | +- Hoisted to the top of its scope |
| 25 | +- Less predictable behavior |
| 26 | +- **Not Recommended in Modern JavaScript** |
| 27 | + |
| 28 | +#### Example of Hoisting |
| 29 | +```javascript |
| 30 | +console.log(x); // Outputs: undefined (not an error) |
| 31 | +var x = 5; |
| 32 | +``` |
| 33 | + |
| 34 | +### 2. `let` (Modern Block-Scoped Declaration) |
| 35 | +```javascript |
| 36 | +let modernVariable = "I'm a block-scoped variable"; |
| 37 | +``` |
| 38 | +#### Characteristics |
| 39 | +- Block-scoped (limited to {} block) |
| 40 | +- Can be updated but not re-declared in same scope |
| 41 | +- More predictable behavior |
| 42 | +- Prevents unintended global variable creation |
| 43 | +- **Recommended for Mutable Variables** |
| 44 | + |
| 45 | +#### Scope Demonstration |
| 46 | +```javascript |
| 47 | +{ |
| 48 | + let blockVariable = "I exist only in this block"; |
| 49 | +} |
| 50 | +// blockVariable is not accessible outside the block |
| 51 | +``` |
| 52 | + |
| 53 | +### 3. `const` (Constant Declaration) |
| 54 | +```javascript |
| 55 | +const unchangeableValue = "I cannot be reassigned"; |
| 56 | +``` |
| 57 | +#### Characteristics |
| 58 | +- Block-scoped |
| 59 | +- Cannot be reassigned after initial value |
| 60 | +- Prevents accidental variable reassignment |
| 61 | +- **Recommended as Default Declaration** |
| 62 | + |
| 63 | +#### Nuanced Behavior with Objects and Arrays |
| 64 | +```javascript |
| 65 | +const person = { name: "Pankaj" }; |
| 66 | +person.name = "Updated Name"; // Allowed |
| 67 | +// person = {}; // This would cause an error |
| 68 | +``` |
| 69 | + |
| 70 | +## 3. Naming Conventions and Rules |
| 71 | + |
| 72 | +### Valid Variable Names |
| 73 | +- Must start with a letter, underscore (_), or dollar sign ($) |
| 74 | +- Can contain letters, numbers, underscores, dollar signs |
| 75 | +- Case-sensitive (`age` and `Age` are different variables) |
| 76 | +- No spaces or special characters allowed |
| 77 | + |
| 78 | +### Recommended Practices |
| 79 | +- Use camelCase for variable names |
| 80 | +- Choose descriptive and meaningful names |
| 81 | +- Avoid single-letter names (except in specific contexts like loops) |
| 82 | + |
| 83 | +#### Good Examples |
| 84 | +```javascript |
| 85 | +let firstName = "Pankaj"; |
| 86 | +let totalStudentCount = 100; |
| 87 | +let isLoggedIn = true; |
| 88 | +``` |
| 89 | + |
| 90 | +#### Bad Examples |
| 91 | +```javascript |
| 92 | +let 2name = "Invalid"; // Starts with number |
| 93 | +let user-name = "Not Good"; // Contains hyphen |
| 94 | +let class = "Reserved word"; // Reserved keyword |
| 95 | +``` |
| 96 | + |
| 97 | +## 4. Data Types in Variables |
| 98 | + |
| 99 | +### Primitive Types |
| 100 | +1. **String**: Text data |
| 101 | + ```javascript |
| 102 | + let greeting = "Hello, World!"; |
| 103 | + ``` |
| 104 | + |
| 105 | +2. **Number**: Numeric values |
| 106 | + ```javascript |
| 107 | + let age = 30; |
| 108 | + let temperature = 98.6; |
| 109 | + ``` |
| 110 | + |
| 111 | +3. **Boolean**: True/False values |
| 112 | + ```javascript |
| 113 | + let isStudent = true; |
| 114 | + ``` |
| 115 | + |
| 116 | +4. **Undefined**: Declared but not assigned |
| 117 | + ```javascript |
| 118 | + let undefinedVar; |
| 119 | + ``` |
| 120 | + |
| 121 | +5. **Null**: Intentional absence of any object value |
| 122 | + ```javascript |
| 123 | + let emptyValue = null; |
| 124 | + ``` |
| 125 | + |
| 126 | +6. **Symbol**: Unique identifier (ES6) |
| 127 | + ```javascript |
| 128 | + let uniqueKey = Symbol('description'); |
| 129 | + ``` |
| 130 | + |
| 131 | +7. **BigInt**: For very large integers |
| 132 | + ```javascript |
| 133 | + let bigNumber = 1234567890123456789012345678901234567890n; |
| 134 | + ``` |
| 135 | + |
| 136 | +### Reference Types |
| 137 | +1. **Object**: Key-value collections |
| 138 | + ```javascript |
| 139 | + let person = { |
| 140 | + name: "Pankaj", |
| 141 | + age: 30, |
| 142 | + skills: ["JavaScript", "React"] |
| 143 | + }; |
| 144 | + ``` |
| 145 | + |
| 146 | +2. **Array**: Ordered list of values |
| 147 | + ```javascript |
| 148 | + let fruits = ["Apple", "Banana", "Cherry"]; |
| 149 | + ``` |
| 150 | + |
| 151 | +## 5. Variable Scope |
| 152 | + |
| 153 | +### Global Scope |
| 154 | +- Variables declared outside any function |
| 155 | +- Accessible everywhere in the code |
| 156 | + |
| 157 | +### Function Scope |
| 158 | +- Variables declared inside a function |
| 159 | +- Accessible only within that function |
| 160 | + |
| 161 | +### Block Scope |
| 162 | +- Variables declared inside {} blocks |
| 163 | +- Limited accessibility |
| 164 | + |
| 165 | +#### Scope Example |
| 166 | +```javascript |
| 167 | +let globalVar = "Global"; |
| 168 | + |
| 169 | +function exampleScope() { |
| 170 | + let functionVar = "Function Scope"; |
| 171 | + |
| 172 | + if (true) { |
| 173 | + let blockVar = "Block Scope"; |
| 174 | + console.log(globalVar); // Accessible |
| 175 | + console.log(functionVar); // Accessible |
| 176 | + console.log(blockVar); // Accessible |
| 177 | + } |
| 178 | + |
| 179 | + // console.log(blockVar); // Would cause an error |
| 180 | +} |
| 181 | +``` |
| 182 | + |
| 183 | +## 6. Best Practices |
| 184 | + |
| 185 | +### Declaration Recommendations |
| 186 | +1. Use `const` by default |
| 187 | +2. Use `let` when value will change |
| 188 | +3. Avoid `var` in modern JavaScript |
| 189 | +4. Initialize variables when declaring |
| 190 | +5. Group related declarations together |
| 191 | + |
| 192 | +### Performance and Memory |
| 193 | +- Declare variables as close to usage as possible |
| 194 | +- Release references when no longer needed |
| 195 | +- Be mindful of variable lifetime |
| 196 | + |
| 197 | +## 7. Type Conversion |
| 198 | + |
| 199 | +### Implicit Conversion |
| 200 | +```javascript |
| 201 | +let result = "5" + 3; // Becomes "53" (string concatenation) |
| 202 | +let math = "5" - 3; // Becomes 2 (numeric subtraction) |
| 203 | +``` |
| 204 | + |
| 205 | +### Explicit Conversion |
| 206 | +```javascript |
| 207 | +let stringNum = "100"; |
| 208 | +let number = Number(stringNum); // Converts to number |
| 209 | +let string = String(number); // Converts to string |
| 210 | +let boolean = Boolean(stringNum); // Converts to boolean |
| 211 | +``` |
| 212 | + |
| 213 | +## Conclusion |
| 214 | +Understanding variables is fundamental to JavaScript programming. Practice and consistent use will make these concepts second nature. |
| 215 | + |
| 216 | +### Quick Reference |
| 217 | +- `const`: Unchanging values |
| 218 | +- `let`: Changing values |
| 219 | +- `var`: Avoid in modern code |
| 220 | + |
| 221 | +**Happy Coding!** 🚀👨💻 |
0 commit comments