Section C. Common operators


C. Common operators

Let's review a few common operators.

Arithmetic operators

The * operator, as you know, performs a multiplication. JavaScript also has the traditional - operator for subtraction and the / operator for division.

JavaScript offers an elegant shorthand for all mathematical operators:

c = c * a; c *= a; 


% Operator

JavaScript also contains the little-used modulo operator %. This operator returns the remainder of a division:

var a = 5 % 2; 


Now a is 1, because 5 modulo 2 is 1; after you've divided 5 by 2, 1 remains.


Both of the statements above multiply c by a and then assign the result to c, but the second one is shorter, and is used quite a lot.

Of course, the +=, -= and /= operators also exist. They do the same thing: they take the value of the left-hand variable, then add, subtract, or divide it by the right-hand value, and assign the result to the left-hand variable.

Finally, there is the unary negation operator - which simply means "Make this number negative":

var a = -3; 


Now a contains the value -3.

++ and --

JavaScript contains a shorthand for adding or subtracting 1: the ++ and -- operators. As we'll see in 5H, these are often used in for loops:

c++; ++c; 


These statements do the same thing: They add 1 to c. But there's a subtle difference between the two. If you put ++ before the variable name, the variable is first incremented (1 is added to it) and the new value is passed to the next operator. If you put the ++ after the variable name, the variable's old value is passed to the next operator, and it is incremented afterwards.

Take this example:

var c = d = 1; var a = c++; var b = ++d; 


Initially c and d are both 1, and the ++ operator increments both to 2. However, a is 1 and b is 2:

  • var a = c++ means "Assign the (old) value of c to a, and then increment c."

  • var b = ++d means "Increment d, and then assign the (new) value to b."

The - operator works in the same way, but it decrements the variable: it subtracts 1.

You'll instinctively use the ++ and - operators correctly 99% of the time. In the remaining 1%, the subtle difference between c++ and ++c will trip you up.

=, ==, and ===

The = operator (used liberally in all code examples) means assign and only assign. This is an assignment:

var x = y * 2; 


JavaScript multiplies y by 2 and assigns the result to variable x. You can also assign the same value to several variables:

var a = b = c = 1; 


Now a, b, and c all have the value 1. That's because the = operator returns the value it just assigned. c = 1 is executed first, and its return value (1) is assigned to b, after which the return value of this operation (still 1) is assigned to a.

= does not mean compare. If you want to compare two values, you must use the equality operator:

if (x == 4) {     // do something } 


This statement is a correct comparison. if (x == 4) means "If x equals 4". If x is indeed equal to 4, then the code block delimited by curly braces {} is executed. If not, it's not executed. The == operator always returns a boolean true (values are equal) or false (values aren't equal). We'll discuss this in more detail in 5G and 5H.

Let's do it wrong:

   if (x = 4) {      // do something  } 


This is not a comparison. The statement x = 4 does not return a boolean, but rather the value that you just assigned to x (which in this example is 4). So this really reads:

   if (4) {      // do something  } 


As we saw in 5B, any number except for 0 or NaN is converted to boolean true, and therefore the if statement would always be executed.

The important distinction between = and == is, once again, something you're going to learn the hard way.

The === operator looks like the two previous operators, but is the identity operator, the stricter version of the equality operator. It requires that its operands have not only the same value, but also the same data type.

Take this code:

var x = 4; var y = '4'; if (x == y) {     alert('x and y are equal'); } if (x === y) {     alert('x and y are identical'); } 


x is the number 4, and y is a string that contains only the character '4'. JavaScript is quite relaxed about this difference, and interprets the string '4' as the number 4 if necessary. Therefore, x == y is true: x is equal to y, since they can both be interpreted as the number 4 (or the string '4', for that matter).

x === y is false, though, since the === operator requires both comparison values to have the same data type. In this example, they don't: x is a number and y is a string. Therefore, x is not identical to y.

In practice, you don't need the === operator; it's rarely necessary to compare data types in common scripts. If you accidentally type one = too much, though, weird things may happen.

!=, <, >, <=, and >=

Sometimes you want to know if one value is not equal to another. This is when you need the inequality operator:

if (x != 4) {     // do something } 


If x is not equal to 4, do something.

JavaScript also has less-than, greater-than, lessthan-or-equal-to, and greater-than-or-equal-to operators. They all return a boolean: comparison correct or incorrect.

if (x < 4) {     alert('x is is less than 4'); } if (x > 4) {     alert('x is greater than 4'); } 


!==

As you might have guessed, there's also a non-identity operator (!==), which is the strict version of the != operator. Two values are not identical if they have different data types, even though they might be equal because they can be interpreted as having the same value.

You rarely need this operator.


if (x <= 4) {     alert('x is less than or equal to 4'); } if (x >= 4) {     alert('x is greater than or equal to 4'); } 


If both operands can be interpreted as numbers, the two values are compared numerically:

var x = '100'; var y = '1000'; if (x < y) {     alert('100 is less than 1000'); } 


Even though x and y are strings, they can both be interpreted as numbers, and therefore JavaScript compares them numerically.

If one of the operands cannot be interpreted as a number, the comparison is alphabetical. Take this example:

var a = 'apple'; var b = 'window'; if (a > b) {     alert('apples are greater than windows'); } else {     alert('windows are greater than apples'); } 


JavaScript determines that windows are greater than apples, because the string 'window' comes after the string 'apple' in normal alphabetical order.

Note that uppercase characters are 'less' than lowercase characters:

var a = 'apple'; var b = 'Window'; if (a > b) {     alert('apples are greater than Windows'); } else {     alert('Windows are greater than apples'); } 


Apples are now greater than Windows, since the string 'Window' comes before the string 'apple' in alphabetical order.

The conditional operator ? :

The conditional operator is unusual, because it works with three values, while all other operators work with one or two values. It performs a check and assigns one of two values to a variable based on that check. For instance:

var a = (b == 0) ? 0 : 1; 


This means "If b is equal to 0, assign 0 to a; otherwise, assign 1 to a." Of course, this code gives the same result:

var a; if (b == 0) {     a = 0; } else {     a = 1; } 


Ternary Operator

The conditional operator is occasionally referred to as the ternary operator, since it works with three operands instead of the usual one or two. As far as I'm concerned, this name is not useful, since it highlights a bit of its syntax instead of its purpose.


The conditional operator is one of the useful shorthands that JavaScript provides, and I always use it for simple checks like the previous one. For instance, in 9F we'll encounter a simple show/hide script. If an element currently has display: block, I want to set its display to none, and vice versa:

var currentValue = this.relatedTag.style.display; var newValue = (currentValue == 'none') ? 'block' : 'none'; 


That closes our preliminary study of operators. We'll encounter many more as this chapter progresses.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net