JavaScript Variables
Variables are used to store data in JavaScript. You can think of them as containers for holding information.
Declaring Variables
In JavaScript, you can declare variables using let, const, or var:
let name = "John"; // A variable that can be reassigned
const age = 25; // A constant that cannot be reassigned
var city = "Paris"; // An older way to declare variables
Reassigning Variables
Variables declared with let can be reassigned:
let name = "John";
name = "Doe"; // Reassigned
console.log(name); // Output: Doe
However, variables declared with const cannot be reassigned:
const age = 25;
age = 30; // Error: Assignment to constant variable
Rules for Variable Names
- Variable names must start with a letter,
_, or$. - They are case-sensitive (
Nameandnameare different). - Avoid using reserved keywords (e.g.,
let,const).
Example
let greeting = "Hello, World!";
console.log(greeting); // Output: Hello, World!