JavaScript supports a variety of operators. Some of them, like those for arithmetic and comparison, are easy for even those new to programming to understand. Others, like the bitwise AND (&), increment (++), and some conditional (?:) operators, may be less obvious to those who have not programmed before. Fortunately for readers of all levels, JavaScript supports few operators that are unique to the language, and the language mimics C, C++, and Java closely in both the kinds of operators it provides and their functionality.
Probably the most basic operator is the assignment operator (=), which is used to assign a value to a variable. Often this operator is used to set a variable to a literal value, for example:
var bigPlanetName = "Jupiter"; var distanceFromSun = 483600000; var visited = true;
Generally, the assignment operator is used to assign a value to a single variable, but it is possible to perform multiple assignments at once by stringing them together with the = operator. For example, the statement
var x = y = z = 7;
sets all three variables to a value of 7.
Assignments can also be used to set a variable to hold the value of an expression. For example, this script fragment demonstrates how variables can be set to the sum of two literal values as well as a combination of literals and variables:
var x = 12 + 5; // x set to 17 var a, b = 3; // a declared but not defined, b set to 3 a = b + 2; // a now contains 5
JavaScript supports all the basic arithmetic operators that readers should be familiar with, including addition (+), subtraction (–), multiplication (*), division (/), and modulus (%, also known as the remainder operator). Table 4-1 details all these operators and presents examples of each.
Operator |
Meaning |
Example |
Result |
---|---|---|---|
+ |
Addition |
var x = 5, y = 7; |
Variable sum contains 12. |
– |
Subtraction |
var x = 5, y = 7; |
Variable diff1 contains –2 while variable diff2 contains 2. |
* |
Multiplication |
var x = 8, y = 4; |
Variable product contains 32. |
/ |
Division |
var x = 36, y = 9, z = 5; |
Variable div1 contains 4 while variable div2 contains 7.2. |
% |
Modulus |
var x = 24, y = 5, z = 6; |
Variable mod1 contains 4 while variable mod2 contains 0. |
Note |
JavaScript itself doesn’t directly support any mathematical operations other than the simple ones discussed here, but through the Math object there are more than enough methods available to accommodate even the most advanced mathematical calculations. The section entitled “Math” in Chapter 7 provides an overview of these features. Complete syntax for the Math object can also be found in Appendix B. |
Note |
Recall from Chapter 3 that numeric values can take on special values like Infinity as a result of becoming too large or small to be representable, or NaN as the result of an undefined operation. Unfortunately, some JavaScript implementations are buggy with respect to handling these values. We found it was possible to throw exceptions and even crash JavaScript-aware browsers on occasion when playing with values in the extreme ranges. Readers are advised that JavaScript is probably not an appropriate language with which to do serious numerical computation. |
The addition operator (+) has a different behavior when operating on strings as opposed to numbers. In this other role, the + operator performs string concatenation. That is, it “stitches” its operands together into a single string. The following,
document.write("JavaScript is " + "great.");
outputs the string "JavaScript is great" to the document.
Of course, you’re not limited to just joining two string variables together. You can join any number of strings or literals together using this operator. For example:
var bookTitle = "The Time Machine"; var author= "H.G. Wells"; var goodBook = bookTitle + " by " + author;
After execution, the variable goodBook contains the string "The Time Machine by H.G. Wells."
The fact that + operates in one way on numbers and another on strings gives rise to a subtlety of JavaScript that often trips up beginners. The subtlety is what happens when you use + in an expression when one operand is a string and the other is not. For example:
var x = "Mixed types" + 10;
The rule is that the interpreter will always treat the + operator as string concatenation if at least one of the operands is a string. So the preceding code fragment results in assignment of the string "Mixed types10" to x. Automatic type conversion was carried out in order to convert the number 10 to a string (see Chapter 3 for more information on type conversion).
There is one further wrinkle with the + operator. Because addition and concatenation in an expression are evaluated by the interpreter from left to right, any leading occurrences of + with two numeric operands (or types that can be automatically converted to numbers) will be treated as addition. For example,
var w = 5; var x = 10; var y = "I am string "; var z = true; alert(w+x+y+z);
displays the following dialog:
The addition of w and x happens before the string concatenation occurs. However, you could force a different order of evaluation with the appropriate application of parentheses. See the section “Operator Precedence and Associativity” later in this chapter for more information.
One trick often used to force + to function as string concatenation is to use the empty string at the beginning of the expression. For example:
var w = 5; var x = 10; var y = "I am string "; var z = true; alert(""+w+x+y+z);
The result is
To force + to operate as addition, you need to use an explicit type conversion function as discussed in Chapter 7.
Note |
JavaScript also supports a great number of other string operations beyond concatenation, but most of these are part of the String object, which is discussed in Chapter 7. |
Another use of the – symbol besides subtraction is to negate a value. As in basic mathematics, placing a minus sign in front of a value will make positive values negative and negative values positive. In this form, it operates on only a single value (or operand) and thus is termed a unary operator. The basic use of the unary negation operator is simple, as illustrated by these examples:
var x = -5; x = -x; // x now equals 5
JavaScript supports the entire range of bitwise operators for the manipulation of bit strings (implemented as the binary representation of integers). JavaScript converts numeric data into a 32-bit integer before performing a bitwise operation on it. The operator in question is then applied bit by bit to this binary representation.
As an example, if we were to perform a bitwise AND operation on 3 and 5, first the numbers would be converted to bit strings of 00000011 for 3 and 00000101 for 5 (we omit the leading 24 0’s). The AND of each digit is then computed, with 1 representing true and 0 representing false. The truth tables for the AND, OR, and XOR (exclusive OR) operations on bits are shown in Table 4-2.
Bit from First Operand |
Bit from Second Operand |
AND Result |
OR Result |
XOR Result |
---|---|---|---|---|
0 |
0 |
0 |
0 |
0 |
0 |
1 |
0 |
1 |
1 |
1 |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
1 |
0 |
So, given the results specified in Table 4-2, if we AND the two bit strings in our example together, we get the value shown here:
This bit string has the decimal value of 1. If you try
alert(5 & 3);
you will see the appropriate result, shown here:
Table 4-3 shows the bitwise operators JavaScript supports, as well as examples of their usage.
Operator |
Description |
Example |
Intermediate Step |
Result |
---|---|---|---|---|
& |
Bitwise AND |
3 & 5 |
00000011 & 00000101 = 00000001 |
1 |
| |
Bitwise OR |
3 | 5 |
00000011 | |
7 |
^ |
Bitwise XOR (exclusive OR) |
3 ^ 5 |
00000011 ^ 00000101 = 00000110 |
6 |
~ |
Bitwise NOT |
~3 |
Invert all bits in a number including the first bit, which is the sign bit, so given ~, 00000011 = 11111100, |
–4 |
The bitwise NOT operator (~) can be a little confusing. Like the other bitwise operators, ~ converts its operand to a 32-bit binary number first. Next, it inverts the bit string, turning all zeros to ones and all ones to zeros. The result in decimal can be somewhat confusing if you are not familiar with binary representations of negative numbers. For example, ~3 returns a value of –4 while ~(–3) returns a value of 2. An easy way to calculate the result manually is to flip all the bits and add 1 to the result. This way of writing negative numbers is the two’s complement representation and is the way most computers represent negative numbers.
Note |
It is possible to use any numeric representation JavaScript supports with a bitwise operator. For example, given that the hex value 0xFF is equivalent to 255, performing a bitwise NOT (~0xFF) results in a value of –256. |
The bitwise operators we’ve covered so far modify the bits of the binary representation of a number, according to bitwise rules of logic. There is another class of bitwise operators that operate on the binary representation of 32-bit integers, but are used to move (shift) bits around rather than set them.
Bitwise shift operators take two operands. The first is the number to be shifted, and the second specifies the number of bit positions by which all the bits in the first operand are to be shifted. The direction of the shift operation is controlled by the operator used, <<<< for left shift and >>>> for right shift. For example, given the left shift operation of 4 <<<<3, the digits making up the number 4 (00000100) will be shifted left three places. Any digits shifted off the left side will be dropped, and the digits to the right will be replaced with zeros. Thus, the result is 00100000, which equals 32.
The supported bitwise shift operators are presented in Table 4-4. The difference between the right shifts >>>> and >>>>>> is significant: The first operator preserves the sign in the bit string by copying the left-most bit to the right while the second uses a zero fill, which does not preserve the sign. For non-negative numbers, the zero-fill right shift (>>>>>>) and sign-propagating right shift (>>>>) yield the same result.
Operator |
Description |
Example |
Intermediate Step |
Result |
---|---|---|---|---|
<< |
Left shift |
4<<3 |
00000100 shifted to the left three spots and filled with zeros results in 00100000. |
32 |
>> |
Right shift with sign extend |
–9>>2 |
11110111 shifted to the right two spots and left-filled with the sign bit results in 11111101. |
–3 |
>>> |
Right shift with zero fill |
32>>>3 |
00100000 shifted to the right three spots and left-filled with 0 results in 00000100. |
4 |
Given the high-level nature of JavaScript when used in a Web browser, the bitwise operators may seem a little out of place. However, remember that JavaScript’s core features are based upon ECMAScript, which is the basis of many languages where low-level bit manipulations may be commonplace. Yet even on the Web, these operators may still have a use. For example, you might find it helpful to use them to extract red, green, or blue color values out of a CSS or XHTML color value. You may also see them used with advanced features for the Event object as discussed in Chapter 11. They aren’t common, but they are part of the language.
Like many languages, JavaScript offers operators that combine an arithmetic or bitwise operation with assignment. Table 4-5 summarizes these operators. These shorthand forms let you express common statements concisely, but are otherwise equivalent to their expanded forms.
Shorthand Assignment |
Expanded Meaning |
Example |
---|---|---|
x += y |
x = x + y |
var x = 5; |
x –= y |
x = x – y |
var x = 5; |
x *= y |
x = x * y |
var x = 5; |
x /= y |
x = x / y |
var x = 5; |
x %= y |
x = x % y |
var x = 5; |
x &= y |
x = x & y |
var x = 5; |
x |= y |
x = x | y |
var x = 5; |
x ^= y |
x = x ^ y |
var x = 5; |
x<<=y |
x=x<<y |
var x = 5; x<<=2; // x is now 20 |
x >>= y |
x = x >> y |
var x = -5; |
x >>>= y |
x = x >>> y |
var x = 5; |
The following section describes a form of assignment even more concise than the operators presented here, for use in another very common task: adding or subtracting one.
The ++ operator is used to increment—or, simply put, to add 1—to its operand. For example, with
var x=3; x++;
the value of x is set to 4. Of course you could also write the increment portion of the previous example as
x=x+1;
Similar to the ++ operator is the –– operator, used to decrement (subtract one from) its operand. So,
var x=3; x--;
leaves a value of 2 in the variable x. Of course, this statement could also have been written the “long” way:
x=x-1;
While adding or subtracting 1 from a variable may not seem terribly useful to those readers new to programming, these operators are very important and are found at the heart of looping structures, which are discussed later in this chapter.
A subtle nuance of the increment (++) and decrement (– –) operators is the position of the operator in relation to the operand. When the increment operator appears on the left of the operand, it is termed a pre-increment, while if it appears on the right, it is a post-increment. The importance of the position of the operator is best illustrated by an example. Consider this script:
var x=3; alert(x++);
You will see
even though the value of x following the alert() statement will be 4. Compare this to the script
var x=3; alert(++x);
The result is more as expected:
And of course the variable x will contain 4 upon conclusion. What’s going on here is that the value the operand takes on in the expression depends on whether the operator is pre- or post-increment. Pre-increment adds one to the value of the operand before using it in the expression. Post-increment adds one to the value after its value has been used. Pre- and post-decrement work the same way.
Note |
It is not possible to combine pre- and post-increment/decrement at the same time. For example, ++x++ results in an error. You should also avoid using pre- and post-increment/decrement more than one time on the same variable in a single expression. Doing so can result in unpredictable behavior. |
A comparison expression evaluates to a Boolean value indicating whether its comparison is true or false. Most of JavaScript’s comparison operators should be familiar from elementary mathematics or from other programming languages. These operators are summarized in Table 4-6.
Operator |
Meaning |
Example |
Evaluates |
---|---|---|---|
< |
Less than |
4 < 8 |
true |
<= |
Less than or equal to |
6 <= 5 |
false |
> |
Greater than |
4 > 3 |
true |
>= |
Greater than or equal to |
5 >= 5 |
true |
!= |
Not equal to |
6 != 5 |
true |
== |
Equal to |
6 == 5 |
false |
=== |
Equal to (and have the same type) |
5 === '5' |
false |
!== |
Not equal to (or don't have the same type) |
5 !== '5' |
true |
A few of these operators warrant further discussion, particularly the equality operators. A common mistake is using a single equal sign (=), which specifies an assignment, when one really wants a double equal sign (==), which specifies the equality comparison. The following example illustrates this problem in action.
var x = 1; var y = 5; if (x = y) alert("Values are the same"); else alert("Values are different");
In this situation, regardless of the values of the variables, the if statement will always evaluate true:
This happens because the value of an assignment statement in an expression is the value that was assigned (in this case, 5, which when automatically converted to a Boolean is true; zero is false and non-zero is true).
More interesting is the situation of values that do not appear the same but compare as such. For example,
alert(5 == "5");
returns a true value because of JavaScript’s automatic type conversion:
Strict equality is handled using the identity operator (===), as shown here. This operator returns true if the operands are equal and of the same type (i.e., it does no type conversion). The script,
alert(5 === "5");
displays false as expected:
Note |
The comparison operators === and !== are not available in Netscape 3 and earlier browsers, though they are available in JavaScript 1.3 and beyond. |
While it is clear what comparison operators mean for numbers, what about strings? For example, is the following expression true?
"thomas" >> "fritz"
When you compare strings, JavaScript evaluates the comparison based on strings’ lexicographic order. Lexicographic order is essentially alphabetic order, with a few extra rules thrown in to deal with upper- and lower-case characters as well as to accommodate strings of different lengths.
The following general rules apply:
Lowercase characters are less than uppercase characters.
Shorter strings are less than longer strings.
Letters occurring earlier in the alphabet are less than those occurring later.
Characters with lower ASCII or Unicode values are less than those with larger values.
The interpreter examines strings on a character-by-character basis. As soon as one of the previous rules applies to the strings in question (for example, the two characters are different), the expression is evaluated accordingly.
The following comparisons are all true:
"b" >> "a" "thomas" >> "fritz" "aaaa" >> "a" "abC" >> "abc"
While this ordering might seem confusing at first blush, it is quite standard and consistent across most programming languages.
As previously stated, the comparison operators described in the preceding section evaluate to Boolean values. The logical operators && (AND), || (OR), and ! (NOT) are useful to combine such values together in order to implement more complicated logic. A description and example of each logical operator are shown in Table 4-7.
Operator |
Description |
Example |
---|---|---|
&& |
Returns true if both operands evaluate true; otherwise returns false. |
var x=true, y=false; |
|| |
Returns true if either operand is true. If both are false, returns false. |
var x=true, y=false; |
! |
If its single operand is true, returns false; otherwise returns true. |
var x=true; |
The most common use of the logical operators is to control the flow of script execution using an if statement (see the section “if Statements” later in this chapter for use of logical operators within an if statement). The conditional operator (?:) discussed next is similar to the if statement and can be used in an expression where an if statement cannot.
The ?: operator is used to create a quick conditional branch. The basic syntax for this operator is
(expression) ? if-true-statement : if-false-statement;
where expression is any expression that will evaluate eventually to true or false. If expression evaluates true, if-true-statement is evaluated. Otherwise, if-false-statement is executed. In this example,
(x >> 5) ? alert("x is greater than 5") : alert("x is less than 5");
an alert dialog will be displayed based upon the value of the variable x. Contextually, if the conditional expression evaluates true, the first statement indicating the value is greater than 5 is displayed; if false, the second statement stating the opposite will be displayed.
At first blush, the ?: operator seems to be simply a shorthand notation for an if statement. The previous example could be rewritten in the more readable but less compact if style syntax, as shown here:
if (x >> 5) alert("x is greater than 5"); else alert("x is less than 5");
In fact, many JavaScript programmers use ?: as a more compact if. For example:
var rolloverAllowed; (document.images) ? rolloverAllowed = true : rolloverAllowed = false;
This compact script sets the variable rolloverAllowed to true or false depending on the existence of the Images[] object. For readability you still may prefer if statements, but the terseness of this operator does make it useful in larger cross-browser scripts that need to perform a great deal of simple conditional checks.
One major difference between ?: and if is that the ?: operator allows only a single statement for the true and false conditions. Thus,
( x >> 5 ) ? alert("Watch out"); alert("This doesn't work") : alert("Error!");
doesn’t work. In fact, because the ?: operator is used to form a single statement, the inclusion of the semicolon (;) anywhere within the expression terminates the statement, and it may ruin it, as shown here:
( x >> 5 ) ? alert("Watch out for the semicolon! "); : alert("The last part will throw an error");
The use of statement blocks as defined by the { } characters will not improve the situation either. The code
( x >> 5 ) ? {alert("using blocks"); alert("doesn't work");} : {alert("error! "); alert("error!");};
will throw errors as well.
Another major difference we’ve already mentioned is that ?: is allowed in an expression, whereas if is not. For example:
var price = 15.00; var total = price * ( (state == "CA") ? 1.0725 : 1.06 ); // add tax
The equivalent if statement would have taken several lines to write.
The comma operator (,) allows multiple expressions to be strung together and treated as one expression. Expressions strung together with commas evaluate to the value of the right-most expression. For example, in this assignment, the final assignment will return the value 56 as a side-effect; thus, the variable a is set to this value:
var a,b,c,d; a = (b=5, c=7, d=56); document.write('a = '+a+' b = '+b+' c = '+c+' d = ' + d);
The comma operator is rarely used in JavaScript outside of variable declarations, except occasionally in complex loops expressions, as shown here:
for (count1=1, count2=4; (count1 + count2) << 10; count1++, count2++) document.write("Count1= " + count1 + " Count2 = " + count2 + "<<br>>");
However, the use of the comma operator is really not suggested.
Note |
Commas are also used to separate parameters in function calls (see Chapter 5). This usage has nothing to do with the comma operator. |
The void operator specifies an expression to be evaluated without returning a value. For example, take the previous example with the comma operator and void it out:
var a,b,c,d; a = void (b=5, c=7, d=56); document.write('a = '+a+' b = '+b+' c = '+c+' d = ' + d);
In this case, the value of a will be undefined, as shown here:
The most common use of the void operator is when using the javascript: pseudo-URL in conjunction with an HTML href attribute. Some browsers, notably early versions of Netscape, had problems when script was used in links. The only way to avoid these problems and force a link click to do nothing when scripting is on is to use void, as shown here:
<<a href="javascript:void (alert('hi!'))">>Click me!<</a>>
As modern browsers implement pseudo-URLs properly, this practice has fallen out of use.
The typeof operator returns a string indicating the data type of its operand. The script fragment here shows its basic use:
a = 3; name = "Howard"; alert(typeof a); // displays number alert(typeof name); // displays string
Table 4-8 shows the values returned by typeof on the basis of the type of value it is presented.
Type |
String Returned by typeof |
---|---|
Boolean | |
Number | |
String | |
Object |
"object" |
Function |
"function" |
Undefined |
"undefined" |
Null |
"object" |
The last set of operators to discuss before moving on to statements are the various object operators.
This section provides a very brief overview of various JavaScript object operators. A more complete discussion can be found in Chapter 6. For now, recall from Chapter 3 that an object is a composite data type that contains any number of properties and methods. Each property has a name and a value, and the period (.) operator is used to access them; for example,
document.lastModified
references the lastModified property of the document object, which contains the date that an HTML document was last modified.
Object properties can also be accessed using array bracket operators ([ ]) enclosing a string containing the name of the property. For example,
document["lastModified"]
is the same as
document.lastModified
A more common use of square brackets is the array index operator ([ ]) used to access the elements of arrays. For example, here we define an array called myArray:
var myArray = [2, 4, 8, 10];
To display the individual elements of the array starting from the first position (0), we would use a series of statements like these:
alert(myArray[0]); alert(myArray[1]); alert(myArray[2]); alert(myArray[3]);
In the previous example, we created an Array object using an array literal. We could have also used the new operator to do so. For example:
var myArray = new Array(2, 4, 8, 10);
The new operator is used to create objects. It can be used both to create user-defined objects and to create instances of built-in objects. The following script creates a new instance of the Date object and places it in the variable today.
var today = new Date(); alert(today);
The result is shown here:
Most languages that allow you to create an object with new allow you to destroy one with delete. This isn’t quite true of JavaScript. To destroy an object, you set it to null. For example, to destroy the object in the previous example, you would write
today = null;
In JavaScript, the delete operator is used to remove a property from an object and to remove an element from an array. The following script illustrates its use for the latter purpose:
var myArray = ['1', '3', '78', '1767']; document.write("myArray before delete = " + myArray); document.write("<<br />>"); delete myArray[2]; // deletes third item since index starts at 0 document.write("myArray after delete = " + myArray);
Notice that the third item, 78, has been removed from the array:
The last operator that is associated with objects is the parentheses operator. This operator is used to invoke an object’s method just as it invokes functions. For example, we have already seen the Document object’s write() method:
document.write("Hello from JavaScript");
In this case, we pass a single parameter, the string "Hello from JavaScript", to the write method so that it is printed to the HTML document. In general, we can invoke arbitrary object methods as follows:
objectname.methodname(optional parameters)
Operators have a predefined order of precedence, that is, order in which they are evaluated in an expression. This is particularly obvious with arithmetic operators and is similar to the evaluation of equations in algebra, where multiplication and division have higher precedence over addition and subtraction. For example, the result of
alert(2 + 3 * 2);
will be 8 because the multiplication is performed before the addition. We see that multiplication has higher precedence than addition. Using parentheses, we can group expressions and force their evaluation in an order of our choice. Parenthesized expressions are evaluated first. For example,
alert((2 + 3) * 2);
will display 10.
Of course, expression evaluation is also influenced by the operator associativity. Associativity essentially means the “direction” in which an expression containing an operator is evaluated. For example, consider the following combination of addition and string concatenation operations:
alert(5 + 6 + "Hello");
The result will be the string "11Hello" rather than "56Hello." Even though the two instances of + would appear to have the same precedence, the + operator is “left associative,” meaning that it is evaluated left to right, so the numeric addition is performed first. Conversely, in this example,
var y; var x = y = 10 * 10;
the multiplication is performed first because assignment (=) is “right associative.” The result is that 100 is computed, then assigned to y, and only then assigned to x.
The precedence and associativity of the various operators in JavaScript is presented in Table 4-9. Note that by computer science tradition, precedence is indicated by a number, with lower numbers indicating higher precedence.
Precedence |
Associativity |
Operator |
Operator Meaning |
---|---|---|---|
Highest: 0 |
Left to right |
. |
Object property access |
0 |
Left to right |
[ ] |
Array access |
0 |
Left to right |
( ) |
Grouping or function or method call |
1 |
Right to left |
++ |
Increment |
1 |
Right to left |
-- |
Decrement |
1 |
Right to left |
– |
Negation |
1 |
Right to left |
~ |
Bitwise NOT |
1 |
Right to left |
! |
Logical NOT |
1 |
Right to left |
delete |
Remove object property or array value |
1 |
Right to left |
new |
Create object |
1 |
Right to left |
typeof |
Determine type |
1 |
Right to left |
void |
Suppress expression evaluation |
2 |
Left to right |
*, /, % |
Multiplication, division, modulus |
3 |
Left to right |
+, – |
Addition, subtraction |
3 |
Left to right |
+ |
String concatenation |
4 |
Left to right |
>> |
Bitwise right-shift with sign |
4 |
Left to right |
>>> |
Bitwise right-shift with zero fill |
4 |
Left to right |
<< |
Bitwise left-shift |
5 |
Left to right |
>, >= |
Greater than, greater than or equal to |
5 |
Left to right |
<, <= |
Less than, less than or equal to |
6 |
Left to right |
== |
Equality |
6 |
Left to right |
!= |
Inequality |
6 |
Left to right |
=== |
Equality with type checking (Identity) |
6 |
Left to right |
!== |
Inequality with type checking (Non-identity) |
7 |
Left to right |
& |
Bitwise AND |
8 |
Left to right |
^ |
Bitwise XOR |
9 |
Left to right |
| |
Bitwise OR |
10 |
Left to right |
&& |
Logical AND |
11 |
Left to right |
|| |
Logical OR |
12 |
Right to left |
? : |
Conditional |
13 |
Right to left |
= |
Assignment |
13 |
Right to left |
*=, /=, %=, +=, –=, <<=, >>=, >>>= , &=, ^=, |= |
Assignment in conjunction with preceding operator |
Lowest: 14 |
Left to right |
, |
Multiple evaluation |
Based on this discussion of operator precedence, you might assume that using parentheses could force the evaluation of all the operators discussed so far. However, this isn’t always the case. For example, consider the post- and pre-increment/decrement operators. As we saw earlier, the results of
var x=3; alert(++x); // shows 4
and
var x=3; alert(x++); // shows 3
show different values because of the difference in when the incrementing happens in relation to the display of the alert dialog. However, if you add parentheses and try to force the incrementing to always happen before the alert is displayed, as shown here,
var x=3; alert((x++)); // shows 3 alert((++x)); // shows 5
you won’t see any difference.
Now that we have covered all the various operators in JavaScript, it is time to combine these together to create statements.