2. Variables in JavaScript
Level: BeginnerDuration: 12m
What Are Variables?
Variables are containers that store data values. Think of them as labeled boxes that hold information your program can read or change.
javascript
let name = "Chrise";
let age = 25;
console.log(name);
console.log(age);Declaring Variables
You can declare variables using var, let, or const. In modern JavaScript, we mostly use let and const because they behave more predictably.
javascript
var city = "Lagos"; // Old way
let score = 90; // New and flexible
const country = "Nigeria"; // Fixed valueUse let when the value might change, and const when it should never change. var is mostly avoided now because it can create confusing scope issues.
Variable Naming Rules
- Names can contain letters, digits, underscores, and dollar signs.
- They must begin with a letter, underscore, or dollar sign.
- They are case-sensitive (age and Age are different).
- Use meaningful names like userName, not x.
Reassigning Values
javascript
let score = 10;
score = 20;
console.log(score); // 20const variables can’t be reassigned. Trying to do so will cause an error.
javascript
const country = "Nigeria";
country = "Ghana"; // ❌ TypeErrorMini Challenge
Create a variable for your favorite programming language, print it to the console, then change it and print again.
Key Takeaway
Use let for flexible values and const for fixed ones. Avoid var unless you specifically need older JavaScript compatibility.