Labs ICT
Pro Login

Variables

JavaScript Variables — Storing Data

Variables are containers for data. Think of them as labeled jars — you put a value in, give it a name, and refer to it later. In old JavaScript, var was the only way to declare variables. It still works, but has quirks you should know about.

var is function-scoped, not block-scoped. It can be redeclared and updated freely. Modern JavaScript prefers let and const, but understanding var is essential for working with older code.

Variable Naming Rules

  • Names can contain letters, digits, underscores, and dollar signs
  • Must begin with a letter, underscore, or dollar sign (not a digit)
  • Case-sensitive: age and Age are different
  • Cannot use reserved keywords like if, for, class
  • Use camelCase by convention: userName, totalPrice

Declaring with var

var name = "Alice";
var age = 25;
var isStudent = true;
console.log(name, age, isStudent);
Try it Yourself →

var Is Function-Scoped

function test() {
  var x = 1;
  if (true) {
    var x = 2; // Same variable!
    console.log(x);
  }
  console.log(x); // 2, not 1
}
test();