by Gordon Mccomb

Expressing yourself in JavaScript

news
Apr 1, 199712 mins
Core JavaJakarta EEJava

Find out how you can use expressions to make your scripts think on their own

Expressions tell JavaScript what you want to do with information youโ€™ve provided. An expression consists of two parts: one or more values, called operands, and an operator that tells JavaScript what you want to do with the operands.

This explanation may sound complex, but as you will soon see, an expression is really nothing more than a simple formula for addition. This column addresses the use of expressions in JavaScript, both for defining the content of variables, as well as for creating more elaborate schemes using other JavaScript constructs. Used in this way, expressions provide a way for your scripts to think on their own (although they may seem to act on their own more than youโ€™d like them to!).

Learning JavaScript

This article is part of the JavaWorld technical content archive. You can learn a lot about JavaScript programming by reading articles in the JavaScript series, just keep in mind that some of the information is likely to be outdated. See โ€œUsing JavaScript and formsโ€ and โ€œUsing JavaScriptโ€™s built-in objectsโ€ for more about programming with JavaScript.

As with all modern programming languages, JavaScript expressions can be divided into several distinct categories: assignment, math, and relational. Assignment expressions assign values to variables; math expressions apply to number values only, with one exception, which weโ€™ll get into later on; and relational expressions apply to numbers and, in some cases, strings.

Weโ€™re going to be examining each of these categories in detail, so we better get started. Weโ€™ll begin with the assignment expressions and the operators used within these expressions.

Assigning values to variables

The following table describes the assignment operators. You will probably use the = assignment operator for the bulk of your JavaScript programs, but itโ€™s nice to know the others are available in case you need them.

OperatorFunction
=Assigns a value to variable (for example, Var=1)
+=Adds a value to a value already in a variable (for example, Var+=1)
-=Subtracts a value from a value already in variable (for example, Var-=1)
*=Multiplies a value with value already in a variable (for example, Var*=1)
/=Divides a value with a value already in a variable (for example, Var/=1)
%=Divides a value with a value already in a variable; returns the remainder (for example, Var%=1)

Note that JavaScript supports additional operators for bitwise operations. Weโ€™ll discuss bitwise operators later in this column.

The first operator in the table, the = assignment operator, lets you assign a new value to variable. If the variable previously contained a value, that value is replaced. Take a look at the following examples:

MyStringVar = "This is a string" // assign text to variable 
MyNumverVar = 100 // assign number to variable 
MyObjectVar = document.form[0] // assign document.form[0] object to variable

The remaining operators in the table are called shorthand assignment operators. These operators let you add, subtract, multiply, and divide values to values already in a variable. The most commonly used shorthand assignment operator, +=, can be used in one of two ways:

  • If the value in the variable and the value to append are numbers, += adds the values.
  • If the value in the variable and the value to append are strings, += combines them into one long string.

Hereโ€™s how the += operator works when the values in question are numbers:

Var = 1;
Var += 5;
// Var now contains 6

You could also write the expression like this:

Var = 1;
Var = Var + 5;

Now hereโ€™s how the += operator works when the values in question are text strings:

Var = "Java";
Var += "Script";
// Var now contains "JavaScript

The remaining shorthand operators let you subtract, multiply, and divide values:

  • Use x -= val for subtracting x times val. This expression is equivalent to x = x - val.
  • Use x *= val for multiplying x times val. This expression is equivalent to x = x * val.
  • Use x /= val for dividing x into val. This expression is equivalent to x = x / val.
  • Use x %= val for dividing x into val, leading the remainder (modulus). This expression is equivalent to x = x % val.

Letโ€™s look at a few examples (the variable Val contains 5 in each case):

Val -= 3        // result: 2
Val *= 3        // result: 15
Val /= 3        // result: 1.666 (etc.)
Val %= 3        // result: 2

Thatโ€™s all there is to assignment operators. Letโ€™s move on to math operators.

More from JavaWorld

Want more Java programming tutorials and news? Get the JavaWorld Enterprise Java newsletter delivered to your inbox.

Performing calculations with math operators

The following table describes the math operators, which you use to perform mathematic calculations with one or more numbers. Note that the operands v1 and v2 are used as substitutes for actual variables/values. Weโ€™ll be using this naming scheme throughout the column.

OperatorFunction
-valueTreats the value as a negative number
v1 + v2Adds values v1 and v2 together; can also be used to connect (concatenate) two or more strings together
v1 โ€“ v2Subtracts value v2 from v1
v1 * v2Multiplies values v1 and v2
v1 / v2Divides value v1 by v2
v1 % v2Divides value v1 by v2; the result is the floating-point remainder of the division
v1++Adds 1 to v1
v1โ€“Subtracts 1 from v1

More about +

In mathematical expressions, the + operator can be used in two ways. When used with numbers, the + operator adds them together. When used with strings, the + operator connects (or concatenates) the strings into a single string.

The ++ and -- operators (the increment/decrement operators borrowed from C, C++, and Java) can be used in a number of ways. The most common is v1++ where you increment the value already in v1 by 1. (Similarly, the instruction v1-- decrements the value already in v1 by 1.) You can actually use the ++ and -- operators before or after the value:

  • When the operator is used after the value (postfix), JavaScript returns the original value and then increments it.
  • When the operator is used before the value (prefix), JavaScript increments the value and returns the incremented result.

Take a look at the following examples. In both examples the Var variable (which is the number 10) is incremented by 1. The RetVal variable, however, contains different values because of the order JavaScript uses in incrementing and returning the value.

RetVal = Var++  // returns 10
RetVal = ++Var  // returns 11

The similar postfix/prefix technique works with the -- operator.

RetVal = Var--  // returns 10
RetVal = --Var  // returns 9

Moving right along, we come to the relational operators.

Comparing values

The following table describes the relational operators, which you use to compare two values to see if they are equal, not equal, greater than, or less than (and sometimes a combination of these).

OperatorFunction
v1 == v2Tests that v1 and v2 are equal (note the two equal signs)
v1 v2Tests that v1 and v2 are not equal
v1 > v2Tests that v1 is greater than v2
v1 >= v2Tests that v1 is greater than or equal to v2
v1 Tests that v1 is less than v2
v1 Tests that v1 is less than or equal to v2
v1 && v2Evaluates the logical AND of v1 and v2
v1 || v2Evaluates the logical OR of v1 and v2
! valueEvaluates the logical NOT of value; the logical NOT is the inverse of an expression (true becomes false, and vice versa)

Relational operators are also known as Boolean (or true/false) operators. Whatever they test, the answer is either yes (true) or no (false). For example, the expression 2==2 would be true, but the expression 2==3 would be false.

Most of the relational operators are pretty straightforward, but the &&, || and ! operators require a little more discussion.

Using the && and || operators

The && (AND) and || (OR) operators work with numbers and expressions that result in a true/false condition. They are not used with strings, unless the strings are a part of a true/false expression. JavaScript balks if you try to use the operators with a string alone. For example, the following expression is not allowed:

This = "Java";
That = "Script";
Result = This && That;

Although this expression may seem logical, it results in an error. Use the following guidelines when dealing with the Boolean operators:

  • Use the && operator to determine if both values in an expression are true. If both A and B are true, the result is true. If A or B is false, the result of the AND expression is false.
  • Use the || operator to determine if either value in an expression is true. If at least one of them is true, the result is true. Only when both values are false is the result of the OR expression false.

Itโ€™s helpful to view the action of the && and || operators with the use of a โ€œtruth table.โ€ A truth table shows all the possible outcomes given to values in an expression. The following truth tables show truth values for Boolean true and false, and also for the numeric digits 0 and 1. JavaScriptโ€™s Boolean operators work the same with either kind of value. (Note: In JavaScript, true/false values are distinct from 1/0.)

AND Truth Table

v1v2Result
false (0)false (0)false (0)
false (0)true (1)false (0)
true (1)false (0)false (0)
true (1)true (1)true (1)

OR Truth Table

v1v2Result
false (0)false (0)false (0)
false (0)true (1)true (1)
true (1)false (0)true (1)
true (1)true (1)true (1)

Using the ! operator

The ! (NOT) operator is used whenever you want to negate a true or false expression. The statement !true becomes false, and !false becomes true.

Ordinarily, you use the ! operator to reverse the outcome of an expression that results in a true/false answer. For example, you might want to test if a certain condition is not met, so you can write a more efficient if statement. (You can also apply the ! operator in for and while loops for additional flexibility.)

Suppose you want to ask the user to respond to a prompt. You do not want them to respond with a blank entry, so you write the following code to allow your JavaScript to redisplay the prompt dialog if the entry box is blank. Notice that Iโ€™ve included an extra if statement to determine when the user chooses the cancel button. This returns a null value, and the loop ends with a break statement.

CtrlLoop=true;
Value="";
while (CtrlLoop) {
 Value=prompt ("Type something", Value);
 if (Value == null)
  break;
 if (Value != "") {
  CtrlLoop=false;
  alert (Value)
 }
}

Using the ? conditional expression statement

JavaScript supports an alternative method to creating conditional expressions. It is a โ€œshorthandโ€ method used in C and some other languages, and is useful if you want to construct a quick and simple test. The syntax is:

<code>(condition)</code> <code> ? istrue : isfalse
</code>

This syntax is pretty simple: condition is the expression you want to test, istrue is what happens if the condition is true, and isfalse is what happens if the condition is false.

Note

You must include statements for both the true and false outcomes, and include the colon character.

The following snippet displays an alert box that has displays an alert that corresponds to what was entered the prompt box:

Ret = prompt ("Type something or click Cancel", "");
(Ret == null) ? alert ("You clicked cancel") : alert ("You typed: "+Ret);

Understanding the bitwise operators

JavaScript supports a unique set of operators that work with numbers only. Specifically, these operators, called bitwise operators, work with the individual bits that make up each number. You probably wonโ€™t be using the bitwise operators too often in your JavaScript programs; however, if you have a programming background, thy may be of use to you in creating more complex scripts. The following table describes the bitwise operators.

OperatorNameFunction
&Bitwise ANDPerforms AND test on each bit in a number
|Bitwise ORPerforms OR test on each bit in a number
^Bitwise XORPerforms XOR test on each bit in a number
Shift leftShifts the values of the bits one or more bits to the left
>>Shift rightShifts the values of the bits one or more bits to the right
>>>Shift right, zero fillSame as Shift right, but also fills the digits to the left with zeros

For example, the following expression displays 8, which is the value of 2 when shifted to the left four bits (binary 10 to binary 1000):

Temp = 2;
Temp = Temp << 2;
alert (Temp);

Using operators and strings

Recall that in a JavaScript program a string is any assortment of text characters. You canโ€™t perform math calculations with text, but you can compare one string of text against another.

With the exception of && and ||, you can use the relational operators with strings for the purpose of comparing them. For instance, you may want to see if two strings are the same, as in:

if ("MyString" == "StringMy");

This expression evaluates to false because they are not the same. In a working script, you would likely construct the string comparison to work with variables, as in:

if (StringVar1 == StringVar2);

JavaScript compares the contents of the two variables and reports true or false, accordingly. When comparing strings, JavaScript is case sensitive; that is, the strings must match exactly, including the case of the individual letters.

While the == operator is used most often in comparing strings, you can also use:

  • !
  • !>
  • >
  • >=

The !> operator is an obvious choice โ€” you can use it to check if one string is not equal to another. But why the others? Donโ€™t they check if one value is greater or lesser than the other? How can one string have โ€œlessโ€ or โ€œmoreโ€ value than the other?

The <</CODE> and > operators do indeed test for greater than and less than, and while they will work with strings, they probably donโ€™t work in the way you may think. Strings โ€” whether they are composed of one character or many โ€” have a numeric value in JavaScript, as described here:

  • If there is one character in the string, the value is the ASCII equivalent of the character. For example, the ASCII equivalent of the letter โ€œAโ€ is 65.
  • If there is more than one character in the string, the value is a composite of the ASCII equivalents of all the characters.

Note that JavaScript can handle more than one operator in an expression, which allows you to string three or more numbers, strings, or variables together to make complex expressions (for example, 5+10/2*7).