JavaScript Variables
๐ง What Are JavaScript Variables?
Variables in JavaScript are used to store data values such as text, numbers, or objects.
Think of a variable like a container that holds information.
๐ท Declaring JavaScript Variables
JavaScript uses three keywords to declare variables:
| Keyword | Feature |
|---|---|
var |
Old way, function-scoped |
let |
Modern, block-scoped |
const |
Constant (cannot be changed) |
โ Example:
๐ Rules for Naming Variables
-
Must start with a letter,
_(underscore), or$ -
Cannot start with a number
-
Cannot use JavaScript reserved words (like
class,return) -
JavaScript is case-sensitive (
nameโName)
Example:
๐งช Assigning Values
You can declare first, then assign later:
Or declare and assign in one line:
๐งฎ Changing Variable Values
let and var values can be updated:
But const cannot be changed:
๐ฅ JavaScript Variables Example with Output
Output:
๐งญ Summary
| Keyword | Can Change Value? | Scope |
|---|---|---|
var |
โ Yes | Function scope |
let |
โ Yes | Block scope |
const |
โ No | Block scope |
