JavaScript Operators

From Techotopia
Revision as of 15:03, 20 April 2007 by Neil (Talk | contribs) (String Operators)

Jump to: navigation, search

JavaScript contains a wide range of operators many of which are used frequently by the typical web designer and some that are not. The purpose of this chapter is to cover the most common operators that a web designer will need in the day to day work of building dynamic web pages.

The key operators for those looking to learn the essentials of JavaScript fall into six categories as follows:

  • Assignment Operators
  • Arithmetic Operators
  • Comparison Operators
  • String Operators
  • Conditional Operators
  • Boolean Operators



Contents


Assignment Operators

In Introducing JavaScript Variables we looked at the '=' assignent operator. This is the most basic of assignment operators and serves to simply assign a value to a variable. For example y = 10 assigns the value of 10 to a variable called y.

The '=' assignment operator does not make any changes to the value before it is assigned to the variable. A number of assignment operators are available, however, that perform arithmetic on the value before assigning it to the variable. These are essentially combined arithmetic and assignment operators. The most common operators of this type, and their "long hand" equivalents are shown below:

Combined OperatorEquivalent
x += yx = x + y
x -= yx = x - y
x /= yx = x / y
x *= yx = x * y
x %= yx = x % y

These combined operators essentially provide a short way of assigning the results of arithmetic expressions between two variables or a variable and a value and having the result assigned to the first variable. For example:

var x = 10;
x += 5; // Assigns a value of 15 to variable x (the same as x = x + 5)

var y = 20;
y -= 10;  // Assigns a value of 10 to variable y (the same as y = y - 10)

var x = 10;
var y = 5;

x /= y; // Assigns a value of 2 to variable x (the same as x = x / y)

Arithmetic Operators

As you might expect, arithmetic operators perform mathematical calculations on both values, and the values assigned to variables. JavaScript arithmetic operators consis of a value to the right and left of the operator. For example:

y = 2 + 5;

adds the value of 2 to the value of 5 and assigns the result (7 in this case) to the variable y.

Arithmetic operatations can also be perform on variables:

y = 10;
x = y + 5;    // Assigns the value 15 to variable x
x = x + y;    // Assigns the value 25 to x (since x now contains the value 15

The key arithmetic operators are:

OperatorDescription
+Addition - Adds values on either side of the operator
-Subtraction - Subtracts right hand value from left hand value
*Multiplication - Multiplies values on either side of the operator
/Division - Divides left hand value by right hand value
%Modulus - Divides left hand value by right hand value and returns remainder

Unary Operators - Incrementing and Decrementing Variable Values

In JavaScript programming it is extremely common to need to incremement and decrement values assigned to variables. The long handed way fo doing this would be:


x = 10;

x = x - 1; // Decreases value of x by 1

x = x + 1; // Increase value of x by 1

A quicker way to perform this is to use the ++ and -- operators - better known as unary operators. The syntax for this is as follows:


--x; // Decreases value of x by 1

++x; // Increase value of x by 1


These operators can also be used increment and decrement a value after an expression as been performed. Suppose you have a varable x which has been assigned a value of 5. You want to add the value of x to a varable called y and then decrement x by 1. One way to do this is as follows:


var x = 5;
var y = 10;

y = y + x; // assigns the value 15 to variable y
++x;       // adds 1 to x to make it 6

By placing the operator after the variable name the variable is automatically incremented or decremented immediately after the expression as been evaluated:


var x = 5;
var y = 10;

y = y + x++; // value of y is now 15, value of x is now 6

// Note that the above exression can be further shortened as follows:

y += x++ // value of y is now 15, value of x is now 6

Comparison Operators

As the name suggests JavaScript Comparison Operators allow you to construct an expression that compares two values and, given the type of comparison specified, returns a true or false value. For example, if you construct a comparison expression to test if two values are identical the result will be true if they are the same and false if they are different. Comparison operators are most often used in decision making during a script using the if statement which is covered in more detail in JavaScript Flow Control and Looping.

The comparison operators available in JavaScript, toghether with examples, are outlined in the following table:

OperatorDescriptionExample
==Equal operator - retuns true if both operands are equal.x == 6 returns true if x is 6
!=Not-equal operator - returns true if operands are not equal.x != 6 returns true if x is not 6
<Less-than operator - returns true if the left hand operand is less than the right hand operand.x < 6 returns true if x is less than 6
>Greater-than operator - returns true if the left hand operand is greater than the right. x > 6 returns true if x is greater than 6
>=Greater-than or equal operator - returns true if the left hand operand is greater than, or equal to the right. x >= 6 returns true if x is either 6, or greater than 6
<=Less-than or equal operator - returns true if the left hand operand is less than, or equal to the right. x <= 6 returns true if x is either equal to 6, or less than 6

String Operators

Once you understand comparison operators the concept of String operators is quite straightforward. The String operators consist of the same comparison operators detailed above. In addition there is one more invaluable operator known as the concatenation operator represented by the + sign. This operator can be used to build strings by joining together multiple strings or strings and other variables.

Let's begin with a simple example using the concatenation operater to build a string from two different strings:


var myString1 = "Hello, ";
var myString2 = "how are you?";

document.write ( myString1 + myString2);

The above example declares and initializes two string variables and then concatenates them in the write statement to create output that reads "Hello, how are you?".

We can take this a step further and use concatenation using not just variables:


var myString1 = "Hello, ";
var myString2 = "how are you?";

document.write ( myString1 + " John, " + myString2);

In this example the output will read "Hello, John, how are you?"

It is also important to understand that concatenation can handle types other than strings. For example when the concatentation operator is used and it encounters a number it will convert that number to a string and join it to the string. For example:


document.write ( "You are visitor number " + 10 );

will output the message "You are visitor number 10". Note, however, that JavaScript evaluates expressions from left to right so if it encounters numbers before it encounters a string it will assume that it has found an arithmetic + rather than a string concatenation +. For example:


document.write ( 10 + 5 + " is my lucky number" );

will cause javaScript to add 10 to 5 to get 15, and then concatenate it with the string to provide a string that reads "15 is my lucky number". Once the string has been encountered in the expression all other + operators are converted to strings and concatenated. In the following example once the string has been found the following operands (i.e the 6 and 1 are converted to strings and joined to the end of the string:


document.write ( 10 + 5 + " is my lucky number. So is " + 6 + 1);

The output from the above will read "15 is my lucky number. So is 61". JavaScript also evaluates expressions from the inner parenthesese to outer parentheses. If you need to perform a calculation after a string appears in an expression, therefore, all you need to do is put ( and ) around the arithemtic expression so that it gets evaluated before the string concatenation:


document.write ( 10 + 5 + " is my lucky number. So is " + (6 + 1));

Remembering that JavaScript will evaluate the expression in the inner parenthesese first we see that it will calculate the value of (6 + 1) before the rest of the expression is evaluated. This will be calculated to be 7 and stored. The rest of the expression will then be evaluated, and then the value 7 will be convered to a string (because it appears to the right of the "my lucky number" value) to create a string that reads "15 is my lucky number. So is 7".