8000 Create Variables.md · aachal28/learn-javascript@5c2b012 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5c2b012

Browse files
authored
Create Variables.md
1 parent 3472a4c commit 5c2b012

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Notes/Basics/Variables.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# JavaScript Variables and Scope 📦
2+
3+
## Variables
4+
Variables are used to store and manipulate data in JavaScript. They serve as containers for storing data values.
5+
6+
## Issues with `var`
7+
In early versions of JavaScript, variables declared with `var` had scope issues. They were function-scoped, which sometimes led to unintended behavior, especially in loops and nested functions.
8+
9+
## Introduction of `let` and `const`
10+
To address the scope issues with `var`, `let` and `const` were introduced in ES6 (ECMAScript 2015). `let` and `const` are block-scoped, meaning they are only accessible within the block (enclosed by curly braces) where they are defined.
11+
12+
## Rules for Variable Declaration
13+
- **Use `const`** for variables that won't be reassigned.
14+
- **Use `let`** for variables that need to be reassigned.
15+
- **Avoid using `var`** due to its function scope behavior. Instead, use `let` or `const` for clearer and safer variable declarations.
16+
17+
18+
### Example: Reassigning Variables with `let`
19+
```javascript
20+
let accountName = "Aachal";
21+
console.log(accountName); // Output: Aachal
22+
23+
accountName = "Sam"; // Reassigning the value of accountName
24+
console.log(accountName); // Output: Sam
25+
```
26+
27+
In this example, accountName is initially assigned the value "Aachal". Later in the code, the value of accountName is changed to "Sam" using the same variable name and the let keyword, indicating that it can be reassigned.

0 commit comments

Comments
 (0)
0