Earlier lessons have discussed function calls, literal values, and variables. Now we need to take a closer look at how they may be combined with operators to create expressions.
This lesson will concentrate on expressions. A subsequent lesson will concentrate on operators.
The resulting value can be a number, a string, or a logical (boolean) value.
Expressions can be very simple or very complex, depending on the need.
Some expressions are used to assign a value to a variable. For
example, the following box shows two expressions that assign a value to
the variable named myVar. The first expression is a simple
assignment which assigns a literal value to a variable. The second
expression is much more complex.
myVar = 10 myVar = ((6 + x) + myFunction(z))/Q |
Sometimes the result of evaluating an expression is not assigned to a variable. These might be referred to an anonymous expressions in keeping with the general use of the term in other areas of programming. An anonymous expression simply evaluates to a value and returns that value to be used in the larger overall expression in which it is included. Since it is never assigned to a variable, it is never given a name; hence the use of the term anonymous.
For example, the second expression from above is repeated below.
myVar = ((6 + x) + myFunction(z))/Q |
This overall expression includes the anonymous expression highlighted in boldface. The anonymous expression will be evaluated and its value will be used to evaluate the larger overall expression, but the value obtained by evaluating the anonymous expression won't be saved anywhere. As soon as the value is used, it will cease to exist.
JavaScript supports three types of expressions which match the three types of data described in an earlier lesson.
According to Netscape, there are a couple of subtle issues involving expressions.
The special keyword null denotes a null value. This is in contrast to variables that have not been assigned a value. Such variables are undefined and will cause a runtime error if used as numbers or as numeric variables.
On the other hand, array elements that have not been assigned a value evaluate to the boolean value false. We will discuss this in more detail when we discuss arrays.
Most of the lessons in this tutorial will contain one or more sample scripts that illustrate the material in this lesson. However, we will forego the sample script in this lesson because virtually every other sample script in every other lesson will contain one or more expressions. There will be no shortage of sample scripts containing expressions.