JavaScript Variables
Variables are used to store data that can be referenced and manipulated in a program.
Introduction to Variables
You can declare JavaScript variables using var, let, or const..
Declaring Variables:
var: Older way, function-scopedlet: Modern way, block-scopedconst: Block-scoped and cannot be reassigned
var name = "Alice";
let age = 25;
const country = "India";
Variable Naming Rules:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter, underscore (_), or dollar sign ($)
- Names are case sensitive
- Reserved words cannot be used as names
- Must begin with a letter,
_, or$ - Case sensitive (
nameandNameare different) - Cannot be a reserved keyword (like
let,if, etc.)
Reassigning Variables
Only var and let variables can be reassigned.
let score = 50;
score = 100; // Valid
const pi = 3.14;
pi = 3.14159; // ❌ Error: Assignment to constant variable
Scope of Variables
- Global Scope: Declared outside functions – accessible everywhere
- Function Scope: Declared inside a function – accessible only within it
- Block Scope:
letandconstinside{ }
function example() {
var a = 10;
let b = 20;
const c = 30;
}
console.log(a); // ❌ Error: a is not defined
Best Practices
- Use
letandconstinstead ofvar - Prefer
constwhen the variable does not change - Choose meaningful variable names
Practice Task
Create a variable for your name, age, and country, and display them using alert():
let name = "John";
let age = 21;
let country = "India";
alert("Name: " + name + "\nAge: " + age + "\nCountry: " + country);