Variable Assignment
In this statment
animal = 'wildebeest';
a variable named animal is set to contain the string 'wildebeest'. However, the = character does NOT represent equality.
Suppose for a second that it does and consider this statement.
x = x + 1;
If this were asserting equality, then this equation would reduce algebraically to 0=1, which would cause the fabric of the universe to come apart. Not good.
In JavaScript, = is the variable assignment operator. In general, here's how it works.
variable_name = expression;
Evaluating varaible assignment is a two step process:
1) Evaluate the expression on the right side.
2) Store the result into the variable on the left side.
A better symbol to represent variable assignment would be like below, where the stuff on the right is evaluated and stored into the variable on the left.
But ← is not a keyboard character, so programming languages can't use it for variable assignment.
variable_name ← expression;
Now the following code makes sense.
var x = 1; // x is assigned the number 1.
x = x + 1; // x is assigned the number 2.
// The right side evaluates to 2, so 2 is assigned to x, replacing the initial value of 1.
When you assign a new value to a variable that already contains a value, the new value simply replaces the initial value.
The following statement is NOT valid. The quantity on the left must be a variable name, not an expression.
x + 1 = x; // ERROR - quantity on left must be a variable name.
The var
keyword is used to declare a variable as a storage location.
Technically when you declare a variable, it can't literally be empty, so it contains the special value undefined.
The first assignment to a new variable is often called initialization, basically assigning the variable it's initial value.
var num; // num is an empty variable.
num = 1; // num is assigned the number 1.
In JavaScript, you can declare and assign an initial value to a variable in one statement.
var num = 1; // Same as above, just in one statement.
You have actually seen it done both ways in the previous examples. Did you notice?