Variables can be thought of as named containers.
In this example, x, y, and z, are variables:
var y = 7;
var z = x + y;
From the example above, you can expect:
- x stores the value 8
- y stores the value 7
- z stores the value 15
Much Like Algebra
In this example, item1, item2, and total, are variables:
var item2 = 7;
var total = itme1 + item2;
In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).
From the example above, you can calculate the total to be 11.
These unique names are called identifiers.
Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter
- Names can also begin with $ and _ (but we will not use it in this tutorial)
- Names are case sensitive (y and Y are different variables)
The Assignment Operator
This is different from algebra. The following does not make sense in algebra:
In programming, text values are called text strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put quotes around a number, it will be treated as a text string.
var person = "Sophie";
var answer = 'Yes I am!';