7. Variables: The Legacy var Keyword
A variable is essentially a container for storing data values. Before 2015, var was the only way to declare variables.
Declaring and Initializing
javascript var message = 'Hello World'; // Declaration and initialization var count; // Declaration only (value is undefined) count = 50;
console.log(message); // Output: Hello World
Variable Reassignment
You can change the value of a var variable at any time.
javascript var score = 100; score = 150; // Reassigned console.log(score); // Output: 150
The Scope Problem with var
var is function-scoped, meaning it is visible throughout the function it is defined in, ignoring block structures like if statements or for loops.
javascript function example() { if (true) { var greeting = 'Hi'; } console.log(greeting); // Output: Hi (This is unexpected behavior!) }
Due to this scoping issue, modern JS prefers let and const.