Working with operators in JavaScript
An operator is a method implemented to replace, modify or combine values represented by variables. With operators, we can evaluate expressionss–JavaScript commands that assign values to variables. In the following expression,
totalAmountDue = totalBeforeTax + (totalBeforeTax * .05);
=, +, * are operators. An expression, as shown above, always has an assignment operator (= sign). An expression can also contain other operators (like +, *, -, /, etc.).
Here’s a comprehensive guide to working with operators in JavaScript:
Arithmetic operators
Arithmetic operators are used to perform simple mathematical calculations. Arithmetic operators can be divided into two categories:
- binary – those operators that work on elements in an expression.
- unary – those operators that work on only one element or variable.
Table 1 lists binary arithmetic operators used in JavaScirpt.
Table 1 Binary arithmetic operators | |||
---|---|---|---|
Operator | Name | Description | Example |
+ | Addition operator | Adds two values together. In JavaScript, this operators is also used to combine two elements. | var webPages = 100; var images = 25; var TotalFiles = webPages + images; var message = “Hello ” + “Sam”; |
– | Subtraction operator | Subtracts one value from another. | var totalAmount = 100; var discount = 3.50; var totalAmountDue = totalAmount – discount; |
/ | Division operator | Divides one value by another | var totalCost = 300; var numOfItems = 7; var averagePricePerItem = totalCost / numOfItems |
* | Multiplication operator | Multiples two values together | var pricePerItem = 5.50; var quantityPurchased = 40; var totalPurchaseCost = pricePerItem * quantityPurchased; |
% | Modulus operator | Determines the remainder after dividing one value by another | var result = 5 % 2; |
Table 2 summarizes unary operators. By using unary operators, you could save some typing; consider the following as an example.
var x = 5;
x = x + 1;
On the first line, we declare a variable called x and assign the number 5. Can you guess what is x after line 2 has been executed? If you think, it is 6; you are correct. Let’s explain how we got 6. On line 1, we set x to 5, and on line 2, we add 5 more to x. In other words, line 2 is saying: x is equal to 5 + 1, which is 6. In this example, note we are using the addition operator (+).
Table 2 unary arithmetic operators | |||
---|---|---|---|
Operator | Operator Name | Description | Example |
++ | Increment operator | Increases a value by 1 | a = 10; b = a++; |
— | Decrement operator | Decreases a value by 1 | a = 10; b = a–; |
– | Negation operator | Changes the sign of a value | a = -10; b = -a; |
In the following example, we will use the increment operator, used to increase the value of a variable by 1.
var x = 5;
x = x++;
So in this example, what is the value of x after line 2 is executed? It is 6 again because the increment operator on line 2 adds 1 to x, which was set to five on line 1. The increment operator comes handy when you have to increase the value of a variable by 1, for instance, when working with loops (executing the same code more than once).
The decrement operator does just the opposite of an increment operator. The decrement operator reduces the value of a variable by 1. The decrement operator also is useful in loops.
The negation operator simply changes the sign of value, assigned to a variable. For instance, in the following
var x = 5;
var y = -x;
the value of y is -5. Why? On line 1, we set x to 5. On line 2, we assign -5 to variable y. Note the value of x will still be 5 after line 2 has executed. Remember a value of a variable changes only when you use the assignment operator. The assignment operator on line 2 changes only the value of y.
Assignment operators
Expressions use assignment operator (= sign) to assign values. JavaScript supports other assignment operators that we can use to assign values to a variable. Those other assignment operators can assign a value in single operation instead of two. If you have worked in a programming language like C++, they should be familiar to you. The following, for instance,
var x = 5;
var y = 15;
x += y;
sets x to 20 on line 3. The += operator simply adds the value of a variable that is on the left of the assignment operator to value of the variable that is on the right hand side of the assignment operator. Thus line 3 above is equivalent to
x = x + y;
Table 3 summarizes assignment operators available in JavaScript. If you are new to programming or programming language like JavaScript, you may want to consider avoiding them until you feel comfortable using them. Instead use the regular assignment operator (=) with a binary or unary arithmetic operators.
Table 3 Summary of assignment operators | |||
---|---|---|---|
Operator | Description | Example | Equivalent to |
= | Assigns the value of a variable on the right hand side (of the =) to the variable on the left of = operator. | a = b; | a = b; |
+= | Adds two variables and assigns the result to a variable on the left (of +=). | a += b; | a = a + b; |
-= | Subtracts two variables and assigns the result to a variable on the left (of -=). | a -= b; | a = a – b; |
/= | Divides the variable on the left (of /=) by the variable on the right (of /=) and assigns the result to the variable on the left. | a /= b; | a = a / b; |
*= | Multiples the variable on the left (of *=) by the variable on the right (of *=) and assigns the result to the variable on the left. | a *= b; | a = a * b; |
%= | Divides the variable on the left (of %=) by the variable on the right (of %=) and assigns the remainder to the variable on the left. | a %= b; | a = a % b; |
Working with conditional statements
A conditional statement uses conditional logic to determine what programming statements to execute. By using some conditional logic (a process of checking conditions), we determine if a certain condition is true or false. If the condition is true, we execute some part of the program. Otherwise, if the condition is false, we use some other part of the program.
To create a condition in JavaScript, we need to write a conditional statement with a comparison operator. (JavaScript also supports logical operators to create complex conditions.) A comparison operator compares the value of one element with that of another. An expression that uses a comparison operator is referred to as a Boolean expression. A Boolean expression evaluates to either true or false.
Let’s consider an example to simplify how to create a conditional statement. Suppose we want to write a small program in JavaScript to determine if 5 is less than 6. To answer that question, we will use an IF statement. In JavaScript, the general syntax for creating an IF statement is:
if (condition) {
some JavaScript code
}
An IF statement starts with the word “if”; next, the condition(s) is listed in parenthesis. After the opening curly brace ( { ), you list the code that you want to execute if the condition is true. All statements, before the closing brace (}), will be executed if the condition is true. If the condition is false, all the statements inside the IF statement will be skipped, not executed.
Let’s write an IF statement that to evaluate whether 5 is less than 6. See the following code:
if (5 < 6) {
document.write ("<br>Condition is true : 5 is less than 6");
}
On line 1 above, we start our IF condition that says check if 5 is less than 6. The less than operator is a comparison operator. On line 2, we have a print statement that will be executed if the condition is true. On line 3, we end our if statement with the closing curly brace. In our IF statement above, 5 < 6 is a Boolean expression because it can be evaluated to either true or false. We know this expression is true so line 2 will be executed. Here is the complete example:
<script language="javascript">
document.write ("checking if 5 is less than 6.......");
if (5 < 6) {
document.write ("<br>Condition is true : 5 is less than 6");
}
document.write ("<br>Done checking");
</script>
Here is the output of the above code:
checking if 5 is less than 6……..
Condition is true : 5 is less than 6
Done checking
As we mentioned before, any statements inside an if block are executed only when the condition is true or is met. Because our condition (5 < 6) is true, the statement inside the IF block is executed to print “Condition is true : 5 is less than 6”. The other print statements (outside of IF block) will execute regardless of the result of the Boolean expression.
In the following example, our Boolean expression evaluates to false (i.e., the condition is false or not met):
if (5 > 6) {
document.write ("<br>Condition is true : 5 is less than 6");
}
So why would the Boolean expression be false in the above example? Well, look closely at our condition. It says if 5 is greater than 6 then execute the statement inside the IF block. We know 5 is not greater than 6, so our Boolean expression (our condition) will evaluate to false. Thus the statement “Condition is true : 5 is less than 6” won’t be printed.
Usually, when a condition is false, we want to execute some other code. For instance, suppose we ask the user to an integer, representing his/her age in years. If we get a valid number, we would use that number in our program. (In other words, our IF condition will be true so statements inside the IF block will be executed.) Otherwise, assume our program cannot use an invalid input. So if it is an invalid input we will again ask the user to enter a valid number. (This part of the code will be added with an ELSE block to the IF block.) Note any code outside of an IF block will be executed whether the condition is false or true.
To recap, any statements that you want to execute when the condition is true, place them inside the IF block; any statements that you want to execute when the condition is false, place them in an ELSE block. Look at the following example
if (5 > 6) {
document.write ("Condition is true : 5 is less than 6");
}
else {
document.write ("Condition is false : 5 is not greater than 6");
}
So in this example, we are saying check if the 5 is greater than 6. If it is true, then, execute line 2; otherwise, execute line 5: document.write (“<br>Condition is false : 5 is not greater than 6″);. Because 5 is not greater than 6, our condition is false and the statement inside the ELSE block will be executed. The following shows the output of the above code:
Condition is true : 5 is less than 6
You could also create two separate IF statements instead of using an ELSE clause, but this is not desirable especially when there are many conditions to check as that will require extra computing power.
Comparison operators
Comparison operators are also called relational operators. These operators are used to construct and test conditions. To use the operator, we need left-hand-side and right-hand-side. The sides represent the values we want to compare and the comparison operator is placed between the values. See the following as an example:

Table 1 lists the 6 comparison operators available in JavaScript. There are six types of comparison operators: equal, not equal to, greater than, less than, greater than or equal to, and less than or equal to. Each of these operators can be used to compare the values of the variables. The result of each of these operators is always either true or false. When using these operators, make sure all of the arguments are of same data type: integers should be compared with integers, strings with strings, and so on.
Table 1 comparison operators
Operator | Description |
---|---|
== | Returns true if both sides are equal. Note the mathematical equal sign (=) is interpreted as an assignment operator in JavaScript. So, in JavaScript, use two equal symbols (==) when you want to find out if one variable is equal to another. |
!= | Returns true if variables are not equal |
> | Returns true if the variable on the left is greater than the variable on the right |
< | Returns true if the variable on the left is less than the variable on the right |
>= | Returns true if the variable on the left is greater than or equal to the value of the variable on the right |
<= | Returns true if the variable on the left is less than or equal to the value of the variable on the right |
Logical operators
The logical operators are used to connect two or more Boolean expressions. Examples of logical operators include the AND operator (&&), OR operator (||), and the NOT operator (!). A condition joined with the AND operator is true only when all of the Boolean expressions are true. For example, in the following
(4 > 2) && (10 < 15)
we have connected two Boolean expressions with the AND operator. For this entire expression to be true, both conditions must be satisfied. Let’s first check the first condition. It asks: is 4 greater than 2? The answer is yes, so our first condition is true. In our second condition, we ask: is 10 less-than 15? This condition is also true. Because both of our conditions are true, the entire expression will be evaluated as true.
If, however, one or more conditions joined with an AND operator is false, then the entire expression is false. Consider this example
(4 < 5) && (3 < 2)
This entire expression will be evaluated as false because both conditions are not true. How? The first condition is true because 4 is less than 5. The second condition, however, is not true because 3 is not less than 2. Because one of the conditions is false, our entire expression will be evaluated as false.
In table 2, we list the logical operators available in JavaScript.
Table 2 logical operators | |
---|---|
Operator | Description |
&& | Returns true only when all expressions are true. |
|| | Returns true only when at least one expression is true. |
! | Returns true if an expression is false, and false if an expression is true. |
Table 3 presents a truth table for the AND operator. As the table shows, an expression is true only when both A and B are true; otherwise the expression is false.
Table 3 truth table for the && operator | ||
---|---|---|
A | B | A && B |
True | True | True |
True | Fasle | False |
False | True | False |
False | False | False |
Table 4 presents the truth table for the OR operator. As the table indicates, the expression is false only when both of the conditions are false. When at least one of the conditions is true, the resulting expression is true.
Table 4 truth table for the || operator | ||
---|---|---|
A | B | A || B |
True | True | True |
True | Fasle | True |
False | True | True |
False | False | False |
Table 5 shows the truth table for the NOT operator. As the truth table shows, the OR operator returns true if the entire expression is false; otherwise the false if the entire expression is true.
Table 5 truth table for the ! operator | ||
---|---|---|
A | B | A ! B |
True | True | False |
True | Fasle | True |
False | True | True |
False | False | True |