Variables are fundamental building blocks in any programming language. They act as containers for storing data that can be referenced and manipulated during program execution.

What is a Variable? 🧮

A variable is a named storage location in memory. Think of it as a labeled box where you can place values (like numbers, text, or objects) and retrieve them later.

Key Characteristics:

  • Name: Identifies the variable (e.g., username, score)
  • Value: The data stored in the variable
  • Type: Defines the kind of data (e.g., integer, string, boolean)

Variable Declaration & Assignment 📝

In most languages, you declare a variable and assign it a value in one step:

age = 25  # Python
let age = 25;  // JavaScript

Naming Rules:

  • Use letters, numbers, and underscores (_)
  • Cannot start with a number
  • Avoid reserved keywords (e.g., if, for)
  • Case-sensitive (e.g., countCount)

Data Types 🧰

Common variable types include:

  • Strings: "Hello, World!"
  • Integers: 42
  • Booleans: true or false
  • Arrays: [1, 2, 3]
  • Objects: { name: "Alice", age: 30 }

Scope & Lifetime 🧪

Variables can have different scopes:

  • Local: Accessible only within a specific block/function
  • Global: Accessible throughout the program
  • Static: Retains its value between function calls

Further Reading 📚

For deeper exploration:

variable_diagram
variables_in_code