A variable is a named container that stores data in a program. In web scripting (JavaScript), we use variables to hold values like numbers, text, or results of calculations that can change as the program runs.
What is a Variable?
Think of a variable as a labeled box in which you can put information. The label (variable name) helps you find the box later, and the information inside (the value) can be changed whenever you need it. For example, a variable called price might hold the value 5000 (representing 5,000 TZS for an item).
Declaring Variables
Before you can use a variable, you must declare it. In JavaScript, there are three ways to declare a variable:
- var – declares a variable that can be changed later (older method)
- let – declares a variable that can be changed later (modern method)
- const – declares a constant whose value cannot be changed after its first assignment
var studentName;
let itemPrice;
const taxRate = 0.1;
Initializing Variables
Initializing means giving a variable its first value. You can declare and initialize a variable in one step, or declare it first and assign a value later.
// Declare and initialize in one step
let age = 15;
var school = "Mwalimu Nyerere Secondary School";
// Declare first, then initialize
let balance;
balance = 10000; // 10,000 TZS
Using Variables in Scripts
Once you have declared and initialized variables, you can use them in calculations, display them to the user, or change their values.
let price = 2500; // Price of one mandazi in TZS
let quantity = 4; // How many mandazis bought
let total = price * quantity; // Calculate total
console.log(total); // Shows: 10000
In this example, the script calculates the total cost of four mandazis at 2,500 TZS each and displays 10,000 TZS.
Practice Tips
- Always choose meaningful names for your variables (like
price, total, name) so your code is easy to understand.
- Use
const for values that should not change, such as tax rates or fixed prices.
- Test your scripts in a browser using the console or by displaying results on a webpage.
Real-life application
In Tanzania, shop owners can use variables in simple web scripts to track their daily sales. For example, a vendor at Mtwara Market can create a script that stores the price of each item (using let or const) and automatically calculates the total earnings from sales, making it easier to manage money without doing calculations manually.