Variables can use short names (such as x and y) or more descriptive names (such as age, sum, totalvolume).
- Variable must start with a letter li>
- Variables can also start with $ and _ symbols (though we don't recommend this)
- Variable names are case sensitive (y and Y are different variables)
x = 5
y = 6
z = x + y
In algebra, we use letters (such as x) to hold values (such as 5).
With the expression z = x + y above, we can calculate the value of z as 11.
|Think of variables as containers for storing data.|
Much Like Algebra
In this precedent, item1, item2, and complete, are variables:
var item2 = 7;
var all out = itme1 + item2;
In programming, much the same as in polynomial math, we use factors (like price1) to hold values.
In programming, much the same as in polynomial math, we use factors in articulations (complete = price1 + price2).
From the precedent above, you can ascertain the aggregate to be 11.
These remarkable names are called identifiers.
Identifiers can be short names (like x and y), or increasingly graphic names (age, entirety, totalVolume).
The general principles for building names for factors (remarkable identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must start with a letter
- Names can likewise start with $ and _ (however we won't utilize it in this tutorial)
- Names are case delicate (y and Y are distinctive variables)
The Assignment Operator
This is not the same as variable based math. The accompanying does not bode well in algebra:
When you assign a text value to a variable, you should enclose the value in double or single quotes.
Do not use quotes when the value you assign to a variable is numeric. If you surround the value with quotes, the value is treated as text.
var individual = "Sophie";
var answer = 'Yes I am!';
One statement, multiple variables
You can declare many variables in one statement. The statement starts with var and the variables are separated by commas:
Declarations can alsospan multiple lines:
age = 30,
job = "carpenter";
Multiple declarations in a statement cannot be assigned the same value:
x, y is undefined and z is 1.
Value = undefined
In computer programs, variables with no value are often declared. A variable declared without a value is actually undefined.
After executing the following statement, the value of the variable carname will be undefined:
After the following two statements are executed, the value of the variable carname is still "Volvo":