In this example, x, y, and z, are variables:
var x = 5;
var y = 6;
var z = x + y;
From the example above, you can expect:
x stores the value 5 y stores the value 6 z stores the value 11
In this example, price1, price2, and total, are variables:
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
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:
This is different from algebra. The following does not make sense in algebra:
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
In programming, text values are called text strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
After the declaration, the variable has no value. (Technically it has the value of undefined)
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:var carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
var x = "5" + 2 + 3;
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
Now try this:
var x = 2 + 3 + "5";