|
| 1 | +## ⚑ Variables |
| 2 | +The variables in JavaScript allows to store data to the names. That can be used again in the code. |
| 3 | + |
| 4 | +*There are 3 common variables in JavaScript.* |
| 5 | + |
| 6 | +### ☴ Overview: |
| 7 | +1. [var](#-var) |
| 8 | +2. [let](#-let) |
| 9 | +3. [const](#-const) |
| 10 | +4. [comparison](#-comparison) |
| 11 | + |
| 12 | +### ✦ Var: |
| 13 | +It declares a function-scoped or globally scoped variable. The scope means accessibility of the data which can be accessible inside function or if defined globally can accessible through out of the code. |
| 14 | + |
| 15 | +*Syntax: `var variableName = value;`* |
| 16 | + |
| 17 | +```javascript |
| 18 | +var x = 10; |
| 19 | +console.log(x); // Output: 10 |
| 20 | +``` |
| 21 | + |
| 22 | +### ✦ Let: |
| 23 | +It declares a block-scoped variable. The data can be accessible block level of the code. |
| 24 | + |
| 25 | +*Syntax: `let variableName = value;`* |
| 26 | + |
| 27 | +```javascript |
| 28 | +function myFunction() { |
| 29 | + let y = 5; |
| 30 | + console.log(y); // Output: 5 |
| 31 | +} |
| 32 | +```` |
| 33 | + |
| 34 | +### ✦ Const: |
| 35 | +It declares a constant variable whose value cannot be changed after it's assigned. |
| 36 | + |
| 37 | +*Syntax: `const variableName = value;`* |
| 38 | + |
| 39 | +```javascript |
| 40 | +const PI = 3.14159; |
| 41 | +console.log(PI); // Output: 3.14159 |
| 42 | +```` |
| 43 | + |
| 44 | +### ✦ Comparison: |
| 45 | +- Scope: |
| 46 | + - `var`: Function-scoped or globally scoped. |
| 47 | + - `let` and `const`: Block-scoped. |
| 48 | +- Redeclaration: |
| 49 | + - `var`: Can be redeclared within the same scope. |
| 50 | + - `let` and `const`: Cannot be redeclared within the same scope. |
| 51 | +- Reassignment: |
| 52 | + - `var` and `let`: Can be reassigned. |
| 53 | + - `const`: Cannot be reassigned. |
| 54 | + |
| 55 | +| var | let | const | |
| 56 | +| --- | --- | --- | |
| 57 | +| For older JavaScript code or when you need function-scoped or globally scoped variables. | For declaring variables within blocks (e.g., functions, loops, conditionals) where you need block-scoped behavior. | For declaring variables that will not change their values, such as constants or immutable objects. This helps prevent accidental modifications and improves code readability. | |
| 58 | + |
| 59 | +--- |
| 60 | +[⇪ To Top](#-variables) |
| 61 | + |
| 62 | +[❮ Previous Topic](./basic-syntax.md)   [Next Topic ❯](./data-types.md) |
| 63 | + |
| 64 | +[⌂ Goto Home Page](../README.md) |
0 commit comments