JavaScript Operators
Previous | Table of Contents | Next |
JavaScript Variable Types | Comments in JavaScript |
Purchase and download the full PDF version of this JavaScript eBook for only $8.99 |
JavaScript contains a wide range of operators, many of which are used frequently by the typical web developer and some that are not. The purpose of this chapter is to cover the most common operators that a web developer 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
- Logical Operators
Assignment Operators
In Introducing JavaScript Variables we looked at the '=' assignment 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.
Combined Operator | Equivalent |
---|---|
x += y | x = x + y |
x -= y | x = x - y |
x /= y | x = x / y |
x *= y | x = x * y |
x %= y | x = x % y |
These combined operators 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 one might expect, arithmetic operators perform mathematical calculations on values and variables. JavaScript arithmetic is comprised of expressions made up of an operator and values to the right and left of that operator (better known as operands). For example in the expression z = x + y, the + is the arithmetic operator, x and y are the operands and the = is the assignment operator:
The following example adds the first operand (2) to the second operand (5) and assigns the result (7) to the variable y.
y = 2 + 5;
Arithmetic operations can also be performed 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:
Operator | Description |
---|---|
+ | Addition - Adds values on either side of the operator |
- | Subtraction - Subtracts right hand operand from left hand operand |
* | Multiplication - Multiplies values on either side of the operator |
/ | Division - Divides left hand operand by right hand operand |
% | Modulus - Divides left hand operand by right hand operand and returns remainder |
Unary Operators - Incrementing and Decrementing Variable Values
In JavaScript programming it is extremely common to need to increment and decrement values assigned to variables. The long handed way of 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 to increment and decrement a value after an expression has been performed. Suppose you have a variable x which has been assigned a value of 5. You want to add the value of x to a variable 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 has 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, return 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, together with examples, are outlined in the following table:
Operator | Description | Example |
---|---|---|
== | Equal operator - returns 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 operator 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 variable types other than strings. For example, when the concatenation 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 );
The above code will output the message "You are visitor number 10". Note, however, that when an expression contains only one type of operator (i.e. only the + operator - see the "Operator Precedence" below for handling expressions with mixed operators) JavaScript evaluates the expression 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" );
When executed, the above code 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 parentheses 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 parentheses around the arithmetic 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 parentheses 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 converted 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".
Conditional Operators
JavaScript uses something called a ternary operator to provide a shortcut way of making decisions in a script. The syntax of the ternary operator is as follows:
[condition]?[true expression]:[false expression]
The way this works is that [condition] is replaced with an expression that will return either true or false. If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action:
var myResult = (x > y) ? x-- : x++;
In the above example, if x is greater than y then the value of x will be decreased by 1. If the x is less than y then the value of x will be increased by 1.
Logical Operators
Logical Operators are also known as Boolean Operators because they evaluate parts of an expression and return a true or false value.
Perhaps the best way to understand how logical operators work is to construct a sentence rather than to look at a script example right away. Let's assume we want to check some aspect of two variables named x and y. Our sentence might read:
If x is less than 10 AND y is greater than 20 display a message.
Here the logical operator is the "AND" part of the sentence. If we were to express this in JavaScript we would use the comparison operators we covered earlier together with the && logical operator:
if ((x < 10) && (y > 20) document.write ("Message");
Similarly if our sentence read:
If x is less than 10 OR y is greater than 20 display a message.
Then we would replace the "OR" with the JavaScript equivalent ||:
if ((x < 10) || (y > 20) document.write ("Message");
The final Logical Operator is the NOT operator which simply inverts the result of an expression. The ! character represents the NOT operator and can be used as follows:
(10 > 1) // returns ''true'' !(10 > 1) // returns ''false'' because we have inverted the result with the logical NOT
Operator Precedence
When using expressions that contain a mixture of operators it is important to be aware that the expression is evaluated in a particular order depending on operator priority. This priority order is outlined in the following table which lists operators from highest priority to lowest:
Operator | Description | Priority |
---|---|---|
* / % | Multiplication, Division, Modulus | Highest |
+ - | Addition, Subtraction | |
<< >> >>> | Bitwise Shift | |
< <= > >= | Comparison | |
== != | Equality | |
&& | Logical AND | |
|| | Logical OR | |
?: | Conditional | |
= += -= *= /= %= | Assignment | |
, | Comma | Lowest |
k = z + x * y;
The use of parentheses can be employed to increase the precedence of part of an expression. For example if we put parentheses around the addition in the expression from above, that part of the expression will be evaluated first. In the following example:
k = (z + x) * y;
z will be added to x and the result will then be multiplied by y.
Purchase and download the full PDF version of this JavaScript eBook for only $8.99 |
Previous | Table of Contents | Next |
JavaScript Variable Types | Comments in JavaScript |