JavaScript Variables
Variables are named containers that store data values so you can reference and update them throughout your program.
What is a variable?
A variable is a label attached to a value in memory. Instead of repeating a raw value like 3.14159 everywhere, you give it a meaningful name such as pi and use that name. When the value behind the name changes, every part of your program that reads the variable sees the updated value automatically.
Modern JavaScript gives you three keywords for declaring variables: let, const, and the older var. As a beginner you should reach for const by default, use let when you know the value will change, and avoid var in new code.
Declaring and assigning
Declaring a variable creates the name; assigning gives it a value. You can do both in one step, or declare first and assign later. The equals sign is the assignment operator, meaning "store the value on the right into the name on the left."
Declaring variables
<!DOCTYPE html>
<html>
<body>
<h2>Declaring variables</h2>
<script>
let firstName = "Ada"; // declare and assign together
let age; // declared, value is undefined
age = 36; // assigned afterwards
const pi = 3.14159; // constant, cannot be reassigned
console.log(firstName, age, pi);
</script>
</body>
</html>The three keywords compared
Rules for naming variables
- Names may contain letters, digits, underscores, and dollar signs.
- A name must begin with a letter, an underscore, or a dollar sign, never a digit.
- Names are case-sensitive, so total and Total are two different variables.
- Reserved words such as let, return, and function cannot be used as names.
- The common convention is camelCase, for example firstName or itemCount.
Using variables in calculations
<!DOCTYPE html>
<html>
<body>
<h2>Using variables in calculations</h2>
<script>
const pricePerItem = 25;
const quantity = 4;
let subtotal = pricePerItem * quantity;
let taxRate = 0.08;
let total = subtotal + subtotal * taxRate;
console.log("Total:", total); // Total: 108
</script>
</body>
</html>Exercise: JavaScript Variables
Which keywords can be used to declare a variable in modern JavaScript?