JavaScript has a number of expressions and operators. Your JavaScript code will probably get a bit more complicated than simple addition or subtraction. In this article, we'll talk about the basic operators and their precedence. We'll talk about numerical and string operators and how you use them in your calculations. We'll also discuss using dates and other operators you'll need to know when working with JavaScript scripts.
Basic Operators and Precedence
Let's take the previous example of a basic addition calculation written in JavaScript.
var x = 10;
var y = 12;
var z = x + y;
Just like math, operators have a precedent. This means that some operators have a higher precedent than others, so when you use a simple calculation within an expression, the higher precedent operator will execute first.
Let's add some multiplication to the above statements. The following code adds multiplication to the addition calculation above.
var x = 10;
var y = 12;
var z = x + y * 2;
Can you figure out the answer to the last statement? If you recall, the asterisk is the multiplication operator. The multiplication operator has precedence over the addition operator. This means that the multiplication part of the calculation executes first, and then the addition statement is executed. This means that when JavaScript executes the above statements, z is assigned the value 34. The y value is multiplied by two and then the x value is added to the result.
You can use parenthesis to group your calculations to ensure that parts of a statement are executed first. For instance, suppose you want JavaScript to add the first two variables and then multiply by two. Using the same example, the following code groups part of the expression to change the calculation precedence.
var x = 10;
var y = 12;
var z = (x + y) * 2;
The parenthesis tell the JavaScript compiler to first add the x and y variables and then multiply by two. The above statement evaluates to z being assigned the value 44. As you can see, precedence can greatly influence the final value of a calculation. If operator precedence isn't taken into consideration, you can have bugs in your calculations unknowingly.
The order of precedence for basic JavaScript operators are as follows:
1. Grouping or parenthesis
2. Incrementing or decrementing (++ or --)
3. Multiplication, division, or the modulus remainder operator
4. Addition and subtraction
5. Equality (greater than or less than)
We discussed calculation operators, but there are also boolean operators when you work with programming languages. Boolean operators return true or false as an expression. If the statement returns true, you usually perform some action against the compared values.
Let's take the following JavaScript expressions.
var x = 10;
var y = 12;
var z = (x + y) * 2;
if (z < 45) message = "Z is less than 45.";
In the above example, we still have our addition and multiplication statement, but we've added an if statement below the calculations. These are the comparison operators. In this expression, the comparison or boolean operator determines if the value of z is less than ( < ) 45. JavaScript also lets you use a greater than operator ( > ), not equal to ( != ), or the equal to ( == ) operator. These operators all compare two values and return true or false. In the above statement, the return value is true, because z is indeed less than 45 in the calculation. If we switched the comparison operator to the greater than symbol, the result boolean value would be false.
It's important to use these comparison operators carefully, because they can be a major concern for logic bugs. As we mentioned, changing the less than symbol to greater than changes the resulting boolean value. This means that the message variable would not be assigned a value, and the results would be wrong. Since z is indeed less than 45, if you use the wrong operator, your code within the "if" statement will not run.
Let's take an example of when you want to use the "equal to" boolean operator.
var x = 10;
var y = 12;
var z = (x + y) * 2;
if (z == 45) message = "Z is equal to 45.";
The same calculations are made but a different comparison operator is used. This comparison operator results in a "false" value, and the message variable expression is not executed. This type of logic is difficult to understand unless you practice with programming language and logic operators frequently.
Notice that the "equal to" boolean operator is different than the assignment operator. If you accidentally used the following code, an error would be thrown.
var x = 10;
var y = 12;
var z = (x + y) * 2;
if (z = 45) message = "Z is equal to 45."; //this would create an JavaScript error
When the JavaScript engine runs the above code, an error is thrown since it does not evaluate to a boolean expression but instead tries to assign z with the value 45. This does not create a valid "if" statement, so a syntax error is returned. This is the main difference between an assignment operator and a comparison operator. If you accidentally use one in place of the other in your code, a syntax error is returned.
Working with Dates
Dates are always a part of your coding if you build a significant script in your site. JavaScript lets you work with days, months, years, seconds, minutes and milliseconds. You'll need all of values when working with dates and then comparing them against other dates. JavaScript includes a class that lets you quickly create a date value without calculating the date yourself. The following example creates a date variable with the current date as the value.
var myDate = new Date();
If you've worked with object-oriented programming, you'll notice that the "new" keyword is used to instantiate the "Date" class constructor. In this expression, the JavaScript compiler gets a new date and assigns the date to the variable "myDate." The constructor also lets you specify a date using milliseconds or a string. For instance, suppose you want to instantiate a new date variable but you want to specify a date entered by your user. The following would create a date variable with a date that you've specified from your online form.
var myDate = new Date('3/2/2018');
Once you create a date variable, you can now use the variable and its methods. For instance, suppose you want to save the date as a string. You can use the "toString" method to convert the date to a string and assign it to a new variable. The following code gives you an example of this method.
var myDate = new Date('3/2/2018');
var dateString = myDate.toString();
In the above example, the "myDate" variable holds an instance of the "Date" class, but the "dateString" variable holds the string with the same value. Strings and dates work differently in programming languages, and you'll need to convert them back and forth to use them. For instance, you need two date variables to compare dates. Suppose you want to see if one date is less than another date. As a string, the logic would not evaluate the way you want it to. However, if you compare two date variables, the compiler knows to compare date versus date and will use the comparison operator to evaluate the result.
Let's take the following example JavaScript code.
var myDate = new Date('3/2/2018');
var myDate2 = new Date();
if (myDate2 > myDate) message = "The current date is greater."
In the above statement, two dates are created and assigned to myDate and myDate2 variables. Then, a comparison is made. If the second date is greater than the first date, the message variable contains a string value that states the current date is greater.
Flow Control
Flow control is the term given to the way JavaScript (or any code for that matter) expressions are executed. Flow control tells you the order in which code executes. Flow control is associated with "if" statements, which we discussed a little bit in the previous chapter. We also discussed equality operators, which play a large role in flow control. Flow control also determines if you have any bugs in your code. Logic bugs are the most difficult to troubleshoot, so you want to get your JavaScript flow control statements correct the first time or your software can cause serious issues with data and users.
Identity and Equality Operators
Identity and equality operators compare two variables or value and return true if these values or variables are equal. These operators can compare values or data type. If you remember, data type determines the type of value a variable will hold. For instance, we discussed a date data type. You can compare two data types to ensure that they are both dates before you execute date functionality on the variables. This type of assurance avoids syntax errors in your code when you define flow control of your expressions.
What about identity operators? If you recall, an equality operator compares values. For instance, the following code compares two string values for equality.
var firstname = "Joe";
var lastname = "Smith";
if (firstname == lastname) message = "First name and last name are the same.";
There are times when you want to compare data types. You might want to ensure that both types are the same before performing an action. The following code shows you how to work with identity operators.
var firstname = "Smith";
var lastname = "Smith";
if (firstname === lastname) message = "First name and last name are the same.";
Notice that there are three equal signs instead of two like the previous section. The previous section compared values. These three equal signs compare data type and values. The previous section returned the boolean value "false," because the values are not equal. However, in this example, the data types are the same as well as the values they hold, so the boolean value "true" is returned. The result is that the message variable contains the string "First name and last name are the same." Notice how the addition of one character can change JavaScript's control flow? This is an essential part of proper logic flow control coding.
You can also use these operators to compare if data types are not equal. The above code snippet lets you know if the two data types are strings. But what happens when you want to identify if the data types are not equal. You could use the above code to compare and run code only if the return value is false, or you can test directly for an unequal data type comparison. The following code compares two values and identifies if they are not the same data type.
var stringNumber = "1";
var integerNumber = 1;
if (stringNumber !== integerNumber) message = "These data types are not the same.";
Notice the exclamation mark in place of the added third equal sign. The exclamation mark is the global "NOT" operator. It negates a comparison and changes the logic. In this example, instead of saying "are these two data types and values equal," the exclamation mark negates the logic and changes the expression to saying "are these two data types and values not equal?" The return result is a boolean value of true, because a number 1 is not the same as a string "1".
You've seen a number of comparisons for both values and data types. What if you want to compare two sets of values? JavaScript logical operators let you combine two comparisons and return one boolean value depending on the type of comparison. We've already covered the logical NOT operator, which is an exclamation mark. Placing the exclamation mark in front of an expression will negate it and change the logic.
There are two other logical operators: the OR operator ( || ), and the AND operator ( && ). These two operators combine expressions in an "if" statement. Let's take a look at the following code.
var firstname = "Joe";
var lastname = "Smith";
if (firstname == lastname && firstname === lastname) message = "First name and last name are the same.";
We used the logical AND operator in the above statement. Notice we've seen the combined two statements before. The first one compares the values of the first and last name variables. The second comparison checks the data types for equality. The && operator returns the boolean value of true only if both statements are in fact true. In other words, both statements are combined and must be true for the entire "if" expression to return the value of true. If both return true, then the message variable is assigned the string value. The above statement actually does return true, because both comparison return true.
The OR operator creates a completely different flow control. With the OR operator, both comparisons are evaluated, but only one of the expressions must return a boolean value of true. Let's use the same expressions we've been using, but let's change the logic to an OR operator value.
var firstname = "Joe";
var lastname = "Smith";
if (firstname == lastname || firstname !== lastname) message = "First name and last name are the same.";
Notice that the second expression has changed to evaluate if the two strings do not have the same data type. Since we know that the first and last name strings are indeed the same data type, the expression evaluates to false. The first expression, however, still evaluates to true. So, we have one expression that evaluates to true and one evaluates to true. If we had used an && expression, the entire "if" statement would evaluate to false since both comparisons did not return true. However, we used the logical OR operator this time. The OR operator only needs one evaluation to return true, because this statement says either the first statement OR the second statement must return to true. Since at least one of them does, the "if" statement returns the boolean value of true and the message string is assigned.
Logical operators can be confusing at first, so practice with some mixing and matching of expressions to get a feel for how control flow works.
Conditions (if-then-else)
We've worked with basic "if" statements. These statements control the flow of your JavaScript execution. We've only used the basic "if" statement, but JavaScript also allows you to execute code when the "if" statement doesn't evaluate to true. You should limit the number of "if" and "if-then" statements, but they are useful when you have two ways you want to go with your control flow.
Let's add some code to the previous examples and add an "else if" and "else" to the statements. Take a look at the following code.
var firstname = "Joe";
var lastname = "Smith";
if (firstname == lastname)
{
message = "First name and last name are the same value.";
}
else if (firstname === lastname)
{
message = "First name and last name have the same data type.";
}
else
{
message = "Neither conditions are true.";
}
The above code snippet is a bit longer than the previous ones we've seen. The first statement compares the first and last name values. As you can see, the values are not the same, so as we've learned, the statement within the brackets will not execute. But we've added an "else-if" block. This statement says "if the first statement isn't true, test this next if statement." The second statement is evaluated for matching data types. If data types don't match, then the default "catch all" phrase "else" is executed. In the above expression, the data types are the same, so the second block is executed. As you can see, you can create numerous logical expressions and if statements that create several different forks in flow control.
JavaScript Loops
Loops are another type of control flow. Loops evaluate an expression and continue to run the embedded expression until the comparison finally evaluates to false. Take a look at the following code.
for (j = 0; j < 10; j++) {
text = text + "The number is " + j + "<br>";
}
The above statement is a for loop. The for loop executes statements until a condition is met. In this example, the condition evaluates when the variable j finally equals 10 after iterating from 0 to 9. This for statement first sets the value of j to 0. Then, a semicolon, which is followed by the condition that must be met to exit the loop. In this example, as long as j is less than 10, the loop continues. The third expression increments j by one using the increment operator, which we've seen previously. As the loop continues, the text variable is assigned a value.
Suppose you want to exit the loop when j reaches a certain value. The "break" keyword stops execution of the for loop prematurely when a condition is met. For instance, suppose you want to exit the loop if the j variable ever evaluates to the value of 3. Take a look at the following code.
for (j = 0; j < 10; j++) {
if (j == 3) { break }
text = text + "The number is " + j + "<br>";
}
In this example, when j reaches the value of three, the loop breaks and any code located after the brackets is executed.
You can also use "while" loops. While loops also evaluate a statement, but they are slightly different in control flow. Instead of incrementing or decrementing numbers for a loop to continue, the while statement lets you loop until a condition is met. While statements are better when you need to work with strings. The following code is an example of a while loop.
while (j < 10) {
text += "The number is " + j;
j++;
}
Notice that this example is similar to the for loop, but the incremented j variable is embedded within the while loop. You only need to evaluate an expression instead of declaring a variable and incrementing it, so you can use these loops to work with strings or other types of variables. Just make sure that the expression is eventually met or you can create an infinite loop. For instance, the following while expression creates an infinite loop that will crash a program.
var j = 1;
while (j < 0) {
text += "The number is " + j;
j++;
}
In this statement, j is initiated to the value of 1 and then the loop begins. The variable is continually incremented by 1, so it will never evaluate to a value less than 0. The result is that your code never stops looping, and the loop will infinitely execute.