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-scoped
  • let: Modern way, block-scoped
  • const: 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 (name and Name are 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: let and const inside { }

function example() {
  var a = 10;
  let b = 20;
  const c = 30;
}
console.log(a); // ❌ Error: a is not defined
            

Best Practices

  • Use let and const instead of var
  • Prefer const when 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);